python-osw-validation 0.2.11__py3-none-any.whl → 0.2.12__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,34 +1,100 @@
1
1
  import os
2
2
  import gc
3
3
  import json
4
- import jsonschema_rs
4
+ import traceback
5
+ from typing import Dict, Any, Optional, List, Tuple
5
6
  import geopandas as gpd
7
+ import jsonschema_rs
8
+
6
9
  from .zipfile_handler import ZipFileHandler
7
- from typing import Dict, Any, Optional, List
8
10
  from .extracted_data_validator import ExtractedDataValidator, OSW_DATASET_FILES
9
11
  from .version import __version__
10
- import traceback
12
+ from .helpers import _feature_index_from_error, _pretty_message, _rank_for
11
13
 
12
14
  SCHEMA_PATH = os.path.join(os.path.dirname(__file__), 'schema')
13
15
 
14
16
 
15
17
  class ValidationResult:
16
- def __init__(self, is_valid: bool, errors: Optional[List[str]] = None):
18
+ """Container for validation outcome.
19
+
20
+ * `errors`: high-level, human-readable strings (legacy behavior).
21
+ * `issues`: per-feature schema problems (former `fixme`), each item:
22
+ { 'filename': str, 'feature_index': Optional[int], 'error_message': List[str] }
23
+ """
24
+
25
+ def __init__(self, is_valid: bool, errors: Optional[List[str]] = None,
26
+ issues: Optional[List[Dict[str, Any]]] = None):
17
27
  self.is_valid = is_valid
18
- self.errors = errors
28
+ if len(errors) == 0:
29
+ self.errors = None
30
+ else:
31
+ self.errors = errors
32
+ self.issues = issues
19
33
 
20
34
 
21
35
  class OSWValidation:
22
36
  default_schema_file_path = os.path.join(SCHEMA_PATH, 'opensidewalks.schema.json')
23
37
 
24
- def __init__(self, zipfile_path: str, schema_file_path=None):
38
+ # per-geometry defaults
39
+ default_point_schema = os.path.join(SCHEMA_PATH, 'Point_schema.json')
40
+ default_line_schema = os.path.join(SCHEMA_PATH, 'Linestring_schema.json')
41
+ default_polygon_schema = os.path.join(SCHEMA_PATH, 'Polygon_schema.json')
42
+
43
+ def __init__(
44
+ self,
45
+ zipfile_path: str,
46
+ schema_file_path=None,
47
+ point_schema_path: Optional[str] = None,
48
+ line_schema_path: Optional[str] = None,
49
+ polygon_schema_path: Optional[str] = None,
50
+ ):
25
51
  self.zipfile_path = zipfile_path
26
- self.extracted_dir = None
27
- self.errors = []
28
- if schema_file_path is None:
29
- self.schema_file_path = OSWValidation.default_schema_file_path
30
- else:
31
- self.schema_file_path = schema_file_path
52
+ self.extracted_dir: Optional[str] = None
53
+ self.errors: List[str] = []
54
+ # per-feature schema issues (formerly `fixme`)
55
+ self.issues: List[Dict[str, Any]] = []
56
+
57
+ # Legacy single schema (if set, used for all)
58
+ self.schema_file_path = schema_file_path # may be None
59
+
60
+ # Per-geometry schemas (with defaults)
61
+ self.point_schema_path = point_schema_path or self.default_point_schema
62
+ self.line_schema_path = line_schema_path or self.default_line_schema
63
+ self.polygon_schema_path = polygon_schema_path or self.default_polygon_schema
64
+
65
+ # ----------------------------
66
+ # Utilities & helpers
67
+ # ----------------------------
68
+ def log_errors(self, message: str, filename: Optional[str] = None, feature_index: Optional[int] = None):
69
+ """Helper to log errors in a consistent format."""
70
+ self.errors.append(message)
71
+ self.issues.append({
72
+ 'filename': filename,
73
+ 'feature_index': feature_index,
74
+ 'error_message': message,
75
+ })
76
+
77
+ # add this small helper inside OSWValidation (near other helpers)
78
+ def _get_colset(self, gdf: Optional[gpd.GeoDataFrame], col: str, filekey: str) -> set:
79
+ """Return set of a column if present; else log and return empty set."""
80
+ if gdf is None:
81
+ return set()
82
+ if col not in gdf.columns:
83
+ self.log_errors(f"Missing required column '{col}' in {filekey}.", filekey, None)
84
+ return set()
85
+ try:
86
+ return set(gdf[col].dropna())
87
+ except Exception:
88
+ # If non-hashable entries sneak in, coerce to str to keep moving
89
+ try:
90
+ return set(map(str, gdf[col].dropna()))
91
+ except Exception:
92
+ self.log_errors(f"Could not create set for column '{col}' in {filekey}.", filekey, None)
93
+ return set()
94
+
95
+ # ----------------------------
96
+ # Schema selection
97
+ # ----------------------------
32
98
 
33
99
  def load_osw_schema(self, schema_path: str) -> Dict[str, Any]:
34
100
  """Load OSW Schema"""
@@ -36,7 +102,11 @@ class OSWValidation:
36
102
  with open(schema_path, 'r') as file:
37
103
  return json.load(file)
38
104
  except Exception as e:
39
- self.errors.append(f'Invalid or missing schema file: {e}')
105
+ self.log_errors(
106
+ message=f'Invalid or missing schema file: {e}',
107
+ filename=schema_path,
108
+ feature_index=None
109
+ )
40
110
  raise Exception(f'Invalid or missing schema file: {e}')
41
111
 
42
112
  def are_ids_unique(self, gdf):
@@ -45,9 +115,36 @@ class OSWValidation:
45
115
  is_valid = len(duplicates) == 0
46
116
  return is_valid, list(duplicates)
47
117
 
118
+ def pick_schema_for_file(self, file_path: str, geojson_data: Dict[str, Any]) -> str:
119
+ if self.schema_file_path:
120
+ return self.schema_file_path
121
+ try:
122
+ features = geojson_data.get('features', [])
123
+ if features:
124
+ gtype = (features[0].get('geometry') or {}).get('type')
125
+ if gtype == 'Point':
126
+ return self.point_schema_path
127
+ if gtype == 'LineString':
128
+ return self.line_schema_path
129
+ if gtype == 'Polygon':
130
+ return self.polygon_schema_path
131
+ except Exception:
132
+ pass
133
+ lower = os.path.basename(file_path).lower()
134
+ if 'node' in lower or 'point' in lower:
135
+ return self.point_schema_path
136
+ if 'edge' in lower or 'line' in lower:
137
+ return self.line_schema_path
138
+ if 'zone' in lower or 'polygon' in lower or 'area' in lower:
139
+ return self.polygon_schema_path
140
+ return self.line_schema_path
141
+
142
+ # ----------------------------
143
+ # Core validation entrypoint
144
+ # ----------------------------
48
145
  def validate(self, max_errors=20) -> ValidationResult:
49
146
  zip_handler = None
50
- OSW_DATASET = {}
147
+ OSW_DATASET: Dict[str, Optional[gpd.GeoDataFrame]] = {}
51
148
  validator = None
52
149
  try:
53
150
  # Extract the zipfile
@@ -55,147 +152,224 @@ class OSWValidation:
55
152
  self.extracted_dir = zip_handler.extract_zip()
56
153
 
57
154
  if not self.extracted_dir:
58
- self.errors.append(zip_handler.error)
59
- return ValidationResult(False, self.errors)
155
+ self.log_errors(
156
+ message=zip_handler.error,
157
+ filename=self.zipfile_path,
158
+ feature_index=None
159
+ )
160
+ return ValidationResult(False, self.errors, self.issues)
60
161
 
61
162
  # Validate the folder structure
62
163
  validator = ExtractedDataValidator(self.extracted_dir)
63
164
  if not validator.is_valid():
64
- self.errors.append(validator.error)
65
- return ValidationResult(False, self.errors)
165
+ self.log_errors(
166
+ message=validator.error,
167
+ filename=self.extracted_dir,
168
+ feature_index=None
169
+ )
170
+ return ValidationResult(False, self.errors, self.issues)
66
171
 
172
+ # Per-file schema validation → populate self.issues (fixme-like)
67
173
  for file in validator.files:
68
174
  file_path = os.path.join(file)
69
175
  if not self.validate_osw_errors(file_path=str(file_path), max_errors=max_errors):
176
+ # mirror legacy behavior: stop early when we hit the cap
70
177
  break
71
178
 
72
179
  if self.errors:
73
- return ValidationResult(False, self.errors)
180
+ return ValidationResult(False, self.errors, self.issues)
74
181
 
75
- # Validate data integrity
182
+ # Load GeoDataFrames for integrity checks
76
183
  for file in validator.files:
77
184
  file_path = os.path.join(file)
78
- osw_file = next(
79
- (osw_file_any for osw_file_any in OSW_DATASET_FILES.keys() if osw_file_any in file_path), '')
80
- OSW_DATASET[osw_file] = gpd.read_file(file_path)
185
+ osw_file = next((osw_key for osw_key in OSW_DATASET_FILES.keys()
186
+ if osw_key in os.path.basename(file_path)), '')
187
+ try:
188
+ gdf = gpd.read_file(file_path)
189
+ except Exception as e:
190
+ self.log_errors(
191
+ message=f"Failed to read '{os.path.basename(file_path)}' as GeoJSON: {e}",
192
+ filename=os.path.basename(file_path),
193
+ feature_index=None
194
+ )
195
+ gdf = None
196
+ if osw_file:
197
+ OSW_DATASET[osw_file] = gdf
81
198
 
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
83
- for osw_file in OSW_DATASET:
84
- is_valid, duplicates = self.are_ids_unique(OSW_DATASET[osw_file])
199
+ # Are all id's unique in each file?
200
+ for osw_file, gdf in OSW_DATASET.items():
201
+ if gdf is None:
202
+ continue
203
+ is_valid, duplicates = self.are_ids_unique(gdf)
85
204
  if not is_valid:
86
- self.errors.append(f"Duplicate _id's found in {osw_file} : {duplicates}")
205
+ self.log_errors(
206
+ message=f"Duplicate _id's found in {osw_file} : {duplicates}",
207
+ filename=osw_file,
208
+ feature_index=None
209
+ )
87
210
 
88
211
  # Create sets of node id's and foreign keys to be used in validation
89
- if 'nodes' in OSW_DATASET:
90
- node_ids = set(OSW_DATASET['nodes']['_id'])
91
- else:
92
- node_ids = set()
212
+ nodes_df = OSW_DATASET.get('nodes')
213
+ edges_df = OSW_DATASET.get('edges')
214
+ zones_df = OSW_DATASET.get('zones')
93
215
 
94
- if 'edges' in OSW_DATASET:
95
- node_ids_edges_u = set(OSW_DATASET['edges']['_u_id'])
96
- node_ids_edges_v = set(OSW_DATASET['edges']['_v_id'])
97
- else:
98
- node_ids_edges_u = set()
99
- node_ids_edges_v = set()
216
+ node_ids = self._get_colset(nodes_df, '_id', 'nodes') if nodes_df is not None else set()
217
+ node_ids_edges_u = self._get_colset(edges_df, '_u_id', 'edges') if edges_df is not None else set()
218
+ node_ids_edges_v = self._get_colset(edges_df, '_v_id', 'edges') if edges_df is not None else set()
100
219
 
101
- if 'zones' in OSW_DATASET:
102
- node_ids_zones_w = set([item for sublist in OSW_DATASET['zones']['_w_id'] for item in sublist])
220
+ # zones: _w_id is list-like per feature → flatten safely
221
+ if zones_df is not None:
222
+ if '_w_id' in zones_df.columns:
223
+ vals = zones_df['_w_id'].dropna().tolist()
224
+ node_ids_zones_w = set(
225
+ item
226
+ for sub in vals
227
+ for item in (sub if isinstance(sub, (list, tuple)) else [sub])
228
+ )
229
+ else:
230
+ self.log_errors("Missing required column '_w_id' in zones.", 'zones', None)
231
+ node_ids_zones_w = set()
103
232
  else:
104
233
  node_ids_zones_w = set()
105
234
 
106
- # Do all node references in _u_id exist in nodes?
107
- unmatched = node_ids_edges_u - node_ids
108
- is_valid = len(unmatched) == 0
109
- if not is_valid:
110
- unmatched_list = list(unmatched)
111
- num_unmatched = len(unmatched_list)
112
- limit = min(num_unmatched, 20)
113
- displayed_unmatched = ', '.join(map(str, unmatched_list[:limit]))
114
- self.errors.append(
115
- f"All _u_id's in edges should be part of _id's mentioned in nodes. "
116
- f"Showing {'20' if num_unmatched > 20 else 'all'} out of {len(unmatched)} unmatched _u_id's: {displayed_unmatched}"
117
- )
235
+ # Cross-file integrity checks (only when we have the prerequisite sets)
236
+ if node_ids and node_ids_edges_u:
237
+ unmatched = node_ids_edges_u - node_ids
238
+ if unmatched:
239
+ unmatched_list = list(unmatched)
240
+ num_unmatched = len(unmatched_list)
241
+ limit = min(num_unmatched, 20)
242
+ displayed_unmatched = ', '.join(map(str, unmatched_list[:limit]))
243
+ self.log_errors(
244
+ message=(f"All _u_id's in edges should be part of _id's mentioned in nodes. "
245
+ f"Showing {'20' if num_unmatched > 20 else 'all'} out of {num_unmatched} "
246
+ f"unmatched _u_id's: {displayed_unmatched}"),
247
+ filename='All',
248
+ feature_index=None
249
+ )
118
250
 
119
- # Do all node references in _v_id exist in nodes?
120
- unmatched = node_ids_edges_v - node_ids
121
- is_valid = len(unmatched) == 0
122
- if not is_valid:
123
- unmatched_list = list(unmatched)
124
- num_unmatched = len(unmatched_list)
125
- limit = min(num_unmatched, 20)
126
- displayed_unmatched = ', '.join(map(str, unmatched_list[:limit]))
127
- self.errors.append(
128
- f"All _v_id's in edges should be part of _id's mentioned in nodes. "
129
- f"Showing {'20' if num_unmatched > 20 else 'all'} out of {len(unmatched)} unmatched _v_id's: {displayed_unmatched}"
130
- )
251
+ if node_ids and node_ids_edges_v:
252
+ unmatched = node_ids_edges_v - node_ids
253
+ if unmatched:
254
+ unmatched_list = list(unmatched)
255
+ num_unmatched = len(unmatched_list)
256
+ limit = min(num_unmatched, 20)
257
+ displayed_unmatched = ', '.join(map(str, unmatched_list[:limit]))
258
+ self.log_errors(
259
+ message=(f"All _v_id's in edges should be part of _id's mentioned in nodes. "
260
+ f"Showing {'20' if num_unmatched > 20 else 'all'} out of {num_unmatched} "
261
+ f"unmatched _v_id's: {displayed_unmatched}"),
262
+ filename='All',
263
+ feature_index=None
264
+ )
131
265
 
132
- # Do all node references in _w_id exist in nodes?
133
- unmatched = node_ids_zones_w - node_ids
134
- is_valid = len(unmatched) == 0
135
- if not is_valid:
136
- unmatched_list = list(unmatched)
137
- num_unmatched = len(unmatched_list)
138
- limit = min(num_unmatched, 20)
139
- displayed_unmatched = ', '.join(map(str, unmatched_list[:limit]))
140
- self.errors.append(
141
- f"All _w_id's in zones should be part of _id's mentioned in nodes. "
142
- f"Showing {'20' if num_unmatched > 20 else 'all'} out of {len(unmatched)} unmatched _w_id's: {displayed_unmatched}"
143
- )
266
+ if node_ids and node_ids_zones_w:
267
+ unmatched = node_ids_zones_w - node_ids
268
+ if unmatched:
269
+ unmatched_list = list(unmatched)
270
+ num_unmatched = len(unmatched_list)
271
+ limit = min(num_unmatched, 20)
272
+ displayed_unmatched = ', '.join(map(str, unmatched_list[:limit]))
273
+ self.log_errors(
274
+ message=(f"All _w_id's in zones should be part of _id's mentioned in nodes. "
275
+ f"Showing {'20' if num_unmatched > 20 else 'all'} out of {num_unmatched} "
276
+ f"unmatched _w_id's: {displayed_unmatched}"),
277
+ filename='All',
278
+ feature_index=None
279
+ )
144
280
 
145
- # 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
146
- for osw_file in OSW_DATASET:
147
- invalid_geojson = OSW_DATASET[osw_file][
148
- (OSW_DATASET[osw_file].geometry.type != OSW_DATASET_FILES[osw_file]['geometry']) | (
149
- OSW_DATASET[osw_file].is_valid == False)]
150
- is_valid = len(invalid_geojson) == 0
151
- if not is_valid:
152
- invalid_ids = list(set(invalid_geojson['_id']))
281
+ # Geometry validation: check geometry type and SFA validity
282
+ for osw_file, gdf in OSW_DATASET.items():
283
+ if gdf is None:
284
+ continue
285
+ expected_geom = OSW_DATASET_FILES.get(osw_file, {}).get('geometry')
286
+ if expected_geom:
287
+ invalid_geojson = gdf[
288
+ (gdf.geometry.type != expected_geom) | (gdf.is_valid == False)
289
+ ]
290
+ else:
291
+ invalid_geojson = gdf[gdf.is_valid == False]
292
+
293
+ if len(invalid_geojson) > 0:
294
+ # Extract IDs if present, else fallback to index
295
+ ids_series = invalid_geojson['_id'] if '_id' in invalid_geojson.columns else invalid_geojson.index
296
+ invalid_ids = list(set(ids_series))
153
297
  num_invalid = len(invalid_ids)
154
298
  limit = min(num_invalid, 20)
155
- displayed_invalid = ', '.join(map(str, invalid_ids[:min(num_invalid, limit)]))
156
- self.errors.append(
157
- f"Showing {'20' if num_invalid > 20 else 'all'} out of {num_invalid} invalid {osw_file} geometries, "
158
- f"id's of invalid geometries: {displayed_invalid}"
159
- )
299
+ displayed_invalid = ', '.join(map(str, invalid_ids[:limit]))
300
+ self.log_errors(
301
+ message=(f"Showing {'20' if num_invalid > 20 else 'all'} out of {num_invalid} "
302
+ f"invalid {osw_file} geometries, id's of invalid geometries: {displayed_invalid}"),
303
+ filename='All',
304
+ feature_index=None
305
+ )
160
306
 
161
307
  # Validate OSW external extensions
162
308
  for file in validator.externalExtensions:
163
309
  file_path = os.path.join(file)
164
310
  file_name = os.path.basename(file)
165
- extensionFile = gpd.read_file(file_path)
311
+ try:
312
+ extensionFile = gpd.read_file(file_path)
313
+ except Exception as e:
314
+ self.log_errors(
315
+ message=f"Failed to read extension '{file_name}' as GeoJSON: {e}",
316
+ filename=file_name,
317
+ feature_index=None
318
+ )
319
+ continue
320
+
166
321
  invalid_geojson = extensionFile[extensionFile.is_valid == False]
167
- is_valid = len(invalid_geojson) == 0
168
- if not is_valid:
322
+ if len(invalid_geojson) > 0:
169
323
  try:
170
- # Safely extract invalid _id or fallback to index if _id is missing
171
324
  invalid_ids = list(set(invalid_geojson.get('_id', invalid_geojson.index)))
172
325
  num_invalid = len(invalid_ids)
173
326
  limit = min(num_invalid, 20)
174
327
  displayed_invalid = ', '.join(map(str, invalid_ids[:limit]))
175
- self.errors.append(
176
- f"Invalid geometries found in extension file `{file_name}`. Showing {limit if num_invalid > 20 else 'all'} of {num_invalid} invalid geometry IDs: {displayed_invalid}"
328
+ self.log_errors(
329
+ message=(f"Invalid geometries found in extension file `{file_name}`. "
330
+ f"Showing {limit if num_invalid > 20 else 'all'} of {num_invalid} "
331
+ f"invalid geometry IDs: {displayed_invalid}"),
332
+ filename=file_name,
333
+ feature_index=None
177
334
  )
178
335
  except Exception as e:
179
- self.errors.append(f"Invalid features found in `{file_name}`, but failed to extract IDs: {e}")
336
+ self.log_errors(
337
+ message=f"Invalid features found in `{file_name}`, but failed to extract IDs: {e}",
338
+ filename=file_name,
339
+ feature_index=None
340
+ )
180
341
 
181
342
  # Optional: Test serializability of extension file
182
343
  try:
183
- for idx, row in extensionFile.drop(columns='geometry').iterrows():
344
+ for _, row in extensionFile.drop(columns='geometry').iterrows():
184
345
  json.dumps(row.to_dict())
185
346
  except Exception as e:
186
- self.errors.append(f"Extension file `{file_name}` has non-serializable properties: {e}")
347
+ self.log_errors(
348
+ message=f"Extension file `{file_name}` has non-serializable properties: {e}",
349
+ filename=file_name,
350
+ feature_index=None
351
+ )
187
352
  break
188
353
 
189
354
  if self.errors:
190
- return ValidationResult(False, self.errors)
355
+ return ValidationResult(False, self.errors, self.issues)
191
356
  else:
192
- return ValidationResult(True)
357
+ return ValidationResult(True, [], self.issues)
358
+
193
359
  except Exception as e:
194
- self.errors.append(f'Unable to validate: {e}')
360
+ self.log_errors(
361
+ message=f'Unable to validate: {e}',
362
+ filename=None,
363
+ feature_index=None
364
+ )
195
365
  traceback.print_exc()
196
- return ValidationResult(False, self.errors)
366
+ return ValidationResult(False, self.errors, self.issues)
197
367
  finally:
198
- del OSW_DATASET
368
+ # Cleanup extracted files
369
+ try:
370
+ del OSW_DATASET
371
+ except Exception:
372
+ pass
199
373
  if zip_handler:
200
374
  zip_handler.remove_extracted_files()
201
375
 
@@ -204,25 +378,72 @@ class OSWValidation:
204
378
 
205
379
  # Additional memory cleanup for geopandas dataframes
206
380
  if validator:
207
- for osw_file in validator.files:
208
- if osw_file in locals():
209
- del osw_file
381
+ try:
382
+ for osw_file in getattr(validator, 'files', []):
383
+ if osw_file in locals():
384
+ del osw_file
385
+ except Exception:
386
+ pass
210
387
  del validator
211
388
  gc.collect()
212
389
 
213
390
  def load_osw_file(self, graph_geojson_path: str) -> Dict[str, Any]:
214
- """Load OSW Data"""
215
391
  with open(graph_geojson_path, 'r') as file:
216
392
  return json.load(file)
217
393
 
218
394
  def validate_osw_errors(self, file_path: str, max_errors: int) -> bool:
219
- """Validate OSW Data against the schema and process all errors"""
395
+ """Validate one OSW GeoJSON against the appropriate schema (streaming).
396
+
397
+ - Keeps legacy `self.errors` capped by `max_errors` (original behavior).
398
+ - While streaming, tracks the *best* error per feature (ranked) and,
399
+ before returning, pushes a single human-friendly message per feature
400
+ into `self.issues` (like your sample: "must include one of: ...").
401
+ """
220
402
  geojson_data = self.load_osw_file(file_path)
221
- validator = jsonschema_rs.Draft7Validator(self.load_osw_schema(self.schema_file_path))
403
+ schema_path = self.pick_schema_for_file(file_path, geojson_data)
404
+ schema = self.load_osw_schema(schema_path)
405
+ validator = jsonschema_rs.Draft7Validator(schema)
406
+
407
+ filename = os.path.basename(file_path)
408
+
409
+ # Per-feature best error accumulator (streaming)
410
+ # feature_idx -> (rank_tuple, error_obj)
411
+ best_by_feature: Dict[Optional[int], Tuple[tuple, Any]] = {}
412
+ feature_order: List[Optional[int]] = [] # preserve first-seen order
413
+
414
+ # Legacy cap
415
+ legacy_count = 0
416
+
417
+ # --- STREAM over errors; STOP as soon as legacy hits the cap ---
418
+ for err in validator.iter_errors(geojson_data):
419
+ # legacy list (for backward compatibility)
420
+ if legacy_count < max_errors:
421
+ self.errors.append(f'Validation error: {getattr(err, "message", "")}')
422
+ legacy_count += 1
423
+ else:
424
+ # We've reached the legacy cap; stop work to match original performance
425
+ break
426
+
427
+ # Track the best error per feature
428
+ fidx = _feature_index_from_error(err)
429
+ r = _rank_for(err)
430
+ prev = best_by_feature.get(fidx)
431
+ if prev is None:
432
+ best_by_feature[fidx] = (r, err)
433
+ feature_order.append(fidx)
434
+ else:
435
+ if r < prev[0]:
436
+ best_by_feature[fidx] = (r, err)
222
437
 
223
- for error in validator.iter_errors(geojson_data):
224
- self.errors.append(f'Validation error: {error.message}')
225
- if len(self.errors) >= max_errors:
226
- return False
438
+ # Build per-feature issues (one concise message per feature) in first-seen order
439
+ for fidx in feature_order:
440
+ _, best_err = best_by_feature[fidx]
441
+ pretty = _pretty_message(best_err, schema)
442
+ self.issues.append({
443
+ "filename": filename,
444
+ "feature_index": fidx if fidx is not None else -1,
445
+ "error_message": [pretty],
446
+ })
227
447
 
448
+ # Mirror original boolean behavior: False when we exactly hit the cap
228
449
  return len(self.errors) < max_errors
@@ -0,0 +1,97 @@
1
+ from typing import Optional
2
+ import re
3
+
4
+ def _feature_index_from_error(err) -> Optional[int]:
5
+ """
6
+ Return the index after 'features' in the instance path, else None.
7
+ Works with jsonschema_rs errors.
8
+ """
9
+ path = list(getattr(err, "instance_path", []))
10
+ for i, seg in enumerate(path):
11
+ if seg == "features" and i + 1 < len(path) and isinstance(path[i + 1], int):
12
+ return path[i + 1]
13
+ return None
14
+
15
+ def _err_kind(err) -> str:
16
+ """
17
+ Best-effort classification of error kind.
18
+ Prefers jsonschema_rs 'kind', falls back to 'validator', then message.
19
+ """
20
+ kobj = getattr(err, "kind", None)
21
+ if kobj is not None:
22
+ return type(kobj).__name__.split("_")[-1] # e.g. 'AnyOf', 'Enum', 'Required'
23
+ v = getattr(err, "validator", None)
24
+ if isinstance(v, str):
25
+ return v[0].upper() + v[1:] # 'anyOf' -> 'AnyOf'
26
+ msg = getattr(err, "message", "") or ""
27
+ return "AnyOf" if "anyOf" in msg else ""
28
+
29
+
30
+ def _clean_enum_message(err) -> str:
31
+ """Compact enum error (strip ‘…or N other candidates’)."""
32
+ msg = getattr(err, "message", "") or ""
33
+ msg = re.sub(r"\s*or\s+\d+\s+other candidates", "", msg)
34
+ return msg.split("\n")[0]
35
+
36
+
37
+ def _pretty_message(err, schema) -> str:
38
+ """
39
+ Convert a jsonschema_rs error to a concise, user-friendly string.
40
+
41
+ Special handling:
42
+ - Enum → compact message
43
+ - AnyOf → summarize the union of 'required' fields across branches:
44
+ "must include one of: <fields>"
45
+ """
46
+ kind = _err_kind(err)
47
+
48
+ if kind == "Enum":
49
+ return _clean_enum_message(err)
50
+
51
+ if kind == "AnyOf":
52
+ # Follow schema_path to the anyOf node; union of 'required' keys in branches.
53
+ sub = schema
54
+ try:
55
+ for seg in getattr(err, "schema_path", []):
56
+ sub = sub[seg]
57
+
58
+ required = set()
59
+
60
+ def crawl(node):
61
+ if isinstance(node, dict):
62
+ if isinstance(node.get("required"), list):
63
+ required.update(node["required"])
64
+ for key in ("allOf", "anyOf", "oneOf"):
65
+ if isinstance(node.get(key), list):
66
+ for child in node[key]:
67
+ crawl(child)
68
+ elif isinstance(node, list):
69
+ for child in node:
70
+ crawl(child)
71
+
72
+ crawl(sub)
73
+
74
+ if required:
75
+ props = ", ".join(sorted(required))
76
+ return f"must include one of: {props}"
77
+ except Exception:
78
+ pass
79
+
80
+ # Default: first line from library message
81
+ return (getattr(err, "message", "") or "").split("\n")[0]
82
+
83
+
84
+ def _rank_for(err) -> tuple:
85
+ """
86
+ Ranking for 'best' error per feature.
87
+ Prefer Enum > (Type/Required/Const) > (Pattern/Minimum/Maximum) > others.
88
+ """
89
+ kind = _err_kind(err)
90
+ order = (
91
+ 0 if kind == "Enum" else
92
+ 1 if kind in {"Type", "Required", "Const"} else
93
+ 2 if kind in {"Pattern", "Minimum", "Maximum"} else
94
+ 3
95
+ )
96
+ length = len(getattr(err, "message", "") or "")
97
+ return (order, length)