python-osw-validation 0.3.5__py3-none-any.whl → 0.3.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,6 +1,7 @@
1
1
  import os
2
2
  import gc
3
3
  import json
4
+ import math
4
5
  import traceback
5
6
  from typing import Dict, Any, Optional, List, Tuple
6
7
  import geopandas as gpd
@@ -11,9 +12,9 @@ from .extracted_data_validator import ExtractedDataValidator, OSW_DATASET_FILES
11
12
  from .version import __version__
12
13
  from .helpers import (
13
14
  _add_additional_properties_hint,
15
+ _err_kind,
14
16
  _feature_index_from_error,
15
17
  _pretty_message,
16
- _rank_for,
17
18
  )
18
19
 
19
20
  SCHEMA_PATH = os.path.join(os.path.dirname(__file__), 'schema')
@@ -129,6 +130,29 @@ class OSWValidation:
129
130
 
130
131
  return None
131
132
 
133
+ def _is_nullish_value(self, value: Any) -> bool:
134
+ if value is None:
135
+ return True
136
+ if isinstance(value, str) and value.strip().lower() in {"null", "nan"}:
137
+ return True
138
+ return isinstance(value, float) and math.isnan(value)
139
+
140
+ def _collect_nullish_property_paths(self, obj: Any, prefix: str = "") -> List[Tuple[str, Any]]:
141
+ paths: List[Tuple[str, Any]] = []
142
+ if isinstance(obj, dict):
143
+ for key, value in obj.items():
144
+ next_prefix = f"{prefix}.{key}" if prefix else str(key)
145
+ paths.extend(self._collect_nullish_property_paths(value, next_prefix))
146
+ return paths
147
+ if isinstance(obj, list):
148
+ for idx, value in enumerate(obj):
149
+ next_prefix = f"{prefix}[{idx}]" if prefix else f"[{idx}]"
150
+ paths.extend(self._collect_nullish_property_paths(value, next_prefix))
151
+ return paths
152
+ if self._is_nullish_value(obj):
153
+ paths.append((prefix or "value", obj))
154
+ return paths
155
+
132
156
  def _contains_disallowed_features_for_02(self, geojson_data: Dict[str, Any]) -> set:
133
157
  """Detect Tree coverage or Custom content in legacy 0.2 datasets.
134
158
 
@@ -197,6 +221,12 @@ class OSWValidation:
197
221
  # Core validation entrypoint
198
222
  # ----------------------------
199
223
  def validate(self, max_errors=20) -> ValidationResult:
224
+ def _finalize(is_valid: bool, errors: Optional[List[str]] = None) -> ValidationResult:
225
+ final_errors = self.errors if errors is None else errors
226
+ final_errors = (final_errors or [])[:max_errors]
227
+ final_issues = (self.issues or [])[:max_errors]
228
+ return ValidationResult(is_valid, final_errors, final_issues)
229
+
200
230
  zip_handler = None
201
231
  OSW_DATASET: Dict[str, Optional[gpd.GeoDataFrame]] = {}
202
232
  validator = None
@@ -211,7 +241,7 @@ class OSWValidation:
211
241
  filename=self.zipfile_path,
212
242
  feature_index=None
213
243
  )
214
- return ValidationResult(False, self.errors, self.issues)
244
+ return _finalize(False)
215
245
 
216
246
  # Validate the folder structure
217
247
  validator = ExtractedDataValidator(self.extracted_dir)
@@ -222,7 +252,7 @@ class OSWValidation:
222
252
  filename=upload_name,
223
253
  feature_index=None
224
254
  )
225
- return ValidationResult(False, self.errors, self.issues)
255
+ return _finalize(False)
226
256
 
227
257
  # Per-file schema validation → populate self.issues (fixme-like)
228
258
  for file in validator.files:
@@ -232,7 +262,7 @@ class OSWValidation:
232
262
  break
233
263
 
234
264
  if self.errors:
235
- return ValidationResult(False, self.errors, self.issues)
265
+ return _finalize(False)
236
266
 
237
267
  # Load GeoDataFrames for integrity checks
238
268
  for file in validator.files:
@@ -414,9 +444,9 @@ class OSWValidation:
414
444
  break
415
445
 
416
446
  if self.errors:
417
- return ValidationResult(False, self.errors, self.issues)
447
+ return _finalize(False)
418
448
  else:
419
- return ValidationResult(True, [], self.issues)
449
+ return _finalize(True, [])
420
450
 
421
451
  except Exception as e:
422
452
  self.log_errors(
@@ -425,7 +455,7 @@ class OSWValidation:
425
455
  feature_index=None
426
456
  )
427
457
  traceback.print_exc()
428
- return ValidationResult(False, self.errors, self.issues)
458
+ return _finalize(False)
429
459
  finally:
430
460
  # Cleanup extracted files
431
461
  try:
@@ -488,6 +518,37 @@ class OSWValidation:
488
518
  except OSError:
489
519
  return False
490
520
 
521
+ filename = os.path.basename(file_path)
522
+
523
+ # Upfront guard: reject null/NaN values in feature properties.
524
+ # This runs before schema validation to surface data quality issues first.
525
+ features = geojson_data.get("features", []) if isinstance(geojson_data, dict) else []
526
+ found_nullish = False
527
+ for idx, feature in enumerate(features):
528
+ if not isinstance(feature, dict):
529
+ continue
530
+ props = feature.get("properties")
531
+ if not isinstance(props, dict):
532
+ continue
533
+ bad_paths = self._collect_nullish_property_paths(props)
534
+ for path, bad_value in bad_paths:
535
+ if len(self.errors) >= max_errors:
536
+ return False
537
+ found_nullish = True
538
+ rendered = f'"{bad_value}"' if isinstance(bad_value, str) else str(bad_value)
539
+ msg = (
540
+ f"Invalid value at '{path}': {rendered}. "
541
+ f"Null/NaN placeholders are not allowed; provide a valid value or remove this property."
542
+ )
543
+ self.errors.append(f"Validation error: {msg}")
544
+ self.issues.append({
545
+ "filename": filename,
546
+ "feature_index": idx,
547
+ "error_message": [msg],
548
+ })
549
+ if found_nullish:
550
+ return False
551
+
491
552
  schema_url = geojson_data.get('$schema')
492
553
  if isinstance(schema_url, str) and '0.2/schema.json' in schema_url:
493
554
  reasons = self._contains_disallowed_features_for_02(geojson_data)
@@ -518,15 +579,9 @@ class OSWValidation:
518
579
  schema = self.load_osw_schema(schema_path)
519
580
  validator = jsonschema_rs.Draft7Validator(schema)
520
581
 
521
- filename = os.path.basename(file_path)
522
-
523
- # Per-feature best error accumulator (streaming)
524
- # feature_idx -> (rank_tuple, error_obj)
525
- best_by_feature: Dict[Optional[int], Tuple[tuple, Any]] = {}
526
- feature_order: List[Optional[int]] = [] # preserve first-seen order
527
-
528
582
  # Legacy cap
529
583
  legacy_count = 0
584
+ collected_issues: List[Dict[str, Any]] = []
530
585
 
531
586
  # --- STREAM over errors; STOP as soon as legacy hits the cap ---
532
587
  for err in validator.iter_errors(geojson_data):
@@ -539,26 +594,28 @@ class OSWValidation:
539
594
  # We've reached the legacy cap; stop work to match original performance
540
595
  break
541
596
 
542
- # Track the best error per feature
597
+ # Keep every issue (no per-feature collapsing)
543
598
  fidx = _feature_index_from_error(err)
544
- r = _rank_for(err)
545
- prev = best_by_feature.get(fidx)
546
- if prev is None:
547
- best_by_feature[fidx] = (r, err)
548
- feature_order.append(fidx)
549
- else:
550
- if r < prev[0]:
551
- best_by_feature[fidx] = (r, err)
552
-
553
- # Build per-feature issues (one concise message per feature) in first-seen order
554
- for fidx in feature_order:
555
- _, best_err = best_by_feature[fidx]
556
- pretty = _pretty_message(best_err, schema)
557
- self.issues.append({
599
+ collected_issues.append({
558
600
  "filename": filename,
559
601
  "feature_index": fidx if fidx is not None else -1,
560
- "error_message": [pretty],
602
+ "error_message": [_pretty_message(err, schema)],
603
+ "_kind": _err_kind(err),
561
604
  })
562
605
 
606
+ # Drop noisy AnyOf summaries when specific field-level errors exist
607
+ # for the same feature.
608
+ has_specific_by_feature: Dict[int, bool] = {}
609
+ for issue in collected_issues:
610
+ fidx = issue["feature_index"]
611
+ if issue.get("_kind") != "AnyOf":
612
+ has_specific_by_feature[fidx] = True
613
+
614
+ for issue in collected_issues:
615
+ if issue.get("_kind") == "AnyOf" and has_specific_by_feature.get(issue["feature_index"], False):
616
+ continue
617
+ issue.pop("_kind", None)
618
+ self.issues.append(issue)
619
+
563
620
  # Mirror original boolean behavior: False when we exactly hit the cap
564
621
  return len(self.errors) < max_errors
@@ -4,6 +4,8 @@ import re
4
4
  _ADDITIONAL_PROPERTIES_RE = re.compile(
5
5
  r"Additional properties are not allowed \('(?P<tag>[^']+)' was unexpected\)"
6
6
  )
7
+ _ENUM_RE = re.compile(r'^(?P<got>.+?) is not one of (?P<allowed>.+)$')
8
+ _TYPE_RE = re.compile(r'^(?P<got>.+?) is not of type (?P<type>.+)$')
7
9
 
8
10
 
9
11
  def _add_additional_properties_hint(msg: str) -> str:
@@ -45,6 +47,118 @@ def _clean_enum_message(err) -> str:
45
47
  msg = re.sub(r"\s*or\s+\d+\s+other candidates", "", msg)
46
48
  return msg.split("\n")[0]
47
49
 
50
+ def _friendly_enum_message(err, schema=None) -> str:
51
+ raw = _clean_enum_message(err)
52
+ match = _ENUM_RE.match(raw)
53
+ if not match:
54
+ return raw
55
+
56
+ path = list(getattr(err, "instance_path", []) or [])
57
+ field = path[-1] if path and isinstance(path[-1], str) else "value"
58
+ got = match.group("got").strip('"')
59
+ allowed = match.group("allowed")
60
+ values = []
61
+ if schema is not None:
62
+ try:
63
+ node = schema
64
+ for seg in list(getattr(err, "schema_path", []) or []):
65
+ node = node[seg]
66
+ if isinstance(node, list):
67
+ values = [str(v) for v in node]
68
+ elif isinstance(node, dict) and isinstance(node.get("enum"), list):
69
+ values = [str(v) for v in node["enum"]]
70
+ except Exception:
71
+ values = []
72
+ if not values:
73
+ values = re.findall(r'"([^"]+)"', allowed)
74
+ if values:
75
+ shown = values[:5]
76
+ allowed_text = "|".join(shown)
77
+ if len(values) > 5:
78
+ allowed_text = f"{allowed_text}| and {len(values) - 5} more"
79
+ else:
80
+ allowed_text = allowed
81
+ return (
82
+ f"Invalid value at '{field}': '{got}'. "
83
+ f"Acceptable values can be one of {allowed_text}, provide a valid value and retry again."
84
+ )
85
+
86
+ def _friendly_type_message(err, schema) -> Optional[str]:
87
+ raw = (getattr(err, "message", "") or "").split("\n")[0]
88
+ if not _TYPE_RE.match(raw):
89
+ return None
90
+
91
+ path = list(getattr(err, "instance_path", []) or [])
92
+ field = path[-1] if path and isinstance(path[-1], str) else "value"
93
+ type_match = _TYPE_RE.match(raw)
94
+ got = type_match.group("got")
95
+ expected_type = type_match.group("type").strip('"')
96
+
97
+ try:
98
+ node = schema
99
+ for seg in list(getattr(err, "schema_path", []) or []):
100
+ node = node[seg]
101
+
102
+ parent = None
103
+ schema_path = list(getattr(err, "schema_path", []) or [])
104
+ if schema_path:
105
+ parent = schema
106
+ for seg in schema_path[:-1]:
107
+ parent = parent[seg]
108
+
109
+ if isinstance(parent, dict) and isinstance(parent.get("enum"), list):
110
+ enum_values = list(parent["enum"])
111
+ shown = enum_values[:5]
112
+ allowed = "|".join(str(v) for v in shown)
113
+ if len(enum_values) > 5:
114
+ allowed = f"{allowed}| and {len(enum_values) - 5} more"
115
+ cleaned_got = got.strip('"')
116
+ return (
117
+ f"Invalid value at '{field}': '{cleaned_got}'. "
118
+ f"Acceptable values can be one of {allowed}, provide a valid value and retry again."
119
+ )
120
+ except Exception:
121
+ pass
122
+
123
+ cleaned_got = got.strip('"')
124
+ return (
125
+ f"Invalid value at '{field}': '{cleaned_got}' . "
126
+ f"Acceptable datatype is {expected_type} ; provide a valid value and retry"
127
+ )
128
+
129
+ def _has_enum_context(err, schema) -> bool:
130
+ """True when this error is an enum mismatch or type mismatch on an enum-constrained field."""
131
+ if _err_kind(err) == "Enum":
132
+ return True
133
+ if _err_kind(err) != "Type":
134
+ return False
135
+ return _friendly_type_message(err, schema) is not None
136
+
137
+
138
+ def _instance_path_str(err) -> str:
139
+ """Render jsonschema instance path as a readable JSON path."""
140
+ path = list(getattr(err, "instance_path", []) or [])
141
+ if not path:
142
+ return ""
143
+
144
+ parts = []
145
+ for seg in path:
146
+ if isinstance(seg, int):
147
+ if parts:
148
+ parts[-1] = f"{parts[-1]}[{seg}]"
149
+ else:
150
+ parts.append(f"[{seg}]")
151
+ else:
152
+ parts.append(str(seg))
153
+ return ".".join(parts)
154
+
155
+
156
+ def _with_path(err, msg: str) -> str:
157
+ path = _instance_path_str(err)
158
+ if not path:
159
+ return msg
160
+ return f"{msg} (at: {path})"
161
+
48
162
 
49
163
  def _pretty_message(err, schema) -> str:
50
164
  """
@@ -58,7 +172,12 @@ def _pretty_message(err, schema) -> str:
58
172
  kind = _err_kind(err)
59
173
 
60
174
  if kind == "Enum":
61
- return _add_additional_properties_hint(_clean_enum_message(err))
175
+ return _add_additional_properties_hint(_friendly_enum_message(err, schema))
176
+
177
+ if kind == "Type":
178
+ friendly_type = _friendly_type_message(err, schema)
179
+ if friendly_type:
180
+ return _add_additional_properties_hint(friendly_type)
62
181
 
63
182
  if kind == "AnyOf":
64
183
  # Follow schema_path to the anyOf node; union of 'required' keys in branches.
@@ -85,24 +204,32 @@ def _pretty_message(err, schema) -> str:
85
204
 
86
205
  if required:
87
206
  props = ", ".join(sorted(required))
88
- return _add_additional_properties_hint(f"must include one of: {props}")
207
+ return _with_path(err, _add_additional_properties_hint(f"must include one of: {props}"))
89
208
  except Exception:
90
209
  pass
91
210
 
92
211
  # Default: first line from library message
212
+ friendly_enum = _friendly_enum_message(err, schema)
213
+ if friendly_enum != _clean_enum_message(err):
214
+ return _add_additional_properties_hint(friendly_enum)
215
+
216
+ friendly_type = _friendly_type_message(err, schema)
217
+ if friendly_type:
218
+ return _add_additional_properties_hint(friendly_type)
219
+
93
220
  default_msg = (getattr(err, "message", "") or "").split("\n")[0]
94
- return _add_additional_properties_hint(default_msg)
221
+ return _with_path(err, _add_additional_properties_hint(default_msg))
95
222
 
96
223
 
97
224
  def _rank_for(err) -> tuple:
98
225
  """
99
226
  Ranking for 'best' error per feature.
100
- Prefer Enum > (Type/Required/Const) > (Pattern/Minimum/Maximum) > others.
227
+ Prefer Type/Required/Const > Enum > (Pattern/Minimum/Maximum) > others.
101
228
  """
102
229
  kind = _err_kind(err)
103
230
  order = (
104
- 0 if kind == "Enum" else
105
- 1 if kind in {"Type", "Required", "Const"} else
231
+ 0 if kind in {"Type", "Required", "Const"} else
232
+ 1 if kind == "Enum" else
106
233
  2 if kind in {"Pattern", "Minimum", "Maximum"} else
107
234
  3
108
235
  )
@@ -1 +1 @@
1
- __version__ = '0.3.5'
1
+ __version__ = '0.3.7'
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python_osw_validation
3
- Version: 0.3.5
3
+ Version: 0.3.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,7 +14,7 @@ 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_rs==0.26.1
17
+ Requires-Dist: jsonschema_rs==0.33.0
18
18
  Requires-Dist: zipfile36==0.1.3
19
19
  Requires-Dist: geopandas==0.14.4
20
20
  Dynamic: author
@@ -44,6 +44,7 @@ This package validates OSW GeoJSON datasets packaged as a ZIP file.
44
44
  - Extracts the provided ZIP file
45
45
  - Finds supported OSW dataset files inside the extracted directory
46
46
  - Validates each file (`edges`, `lines`, `nodes`, `points`, `polygons`, and `zones`) against the matching schema
47
+ - Performs an upfront data-quality check for null-like placeholders in feature properties (for example `null`, `NaN`, `"null"`, `"nan"`)
47
48
  - Runs cross-file integrity checks such as duplicate `_id` detection and edge or zone references back to nodes
48
49
  - Returns a `ValidationResult` object with `is_valid`, `errors`, and `issues`
49
50
 
@@ -64,13 +65,24 @@ validator = OSWValidation(zipfile_path='<Zip file path>')
64
65
  result = validator.validate()
65
66
  print(result.is_valid)
66
67
  print(result.errors) # returns up to the first 20 high-level errors by default
67
- print(result.issues) # per-file or per-feature issues
68
+ print(result.issues) # detailed per-feature issues, capped to first 20 by default
68
69
 
69
70
  result = validator.validate(max_errors=10)
70
71
  print(result.is_valid)
71
72
  print(result.errors) # returns up to the first 10 high-level errors
73
+ print(result.issues) # capped by the same max_errors limit
72
74
  ```
73
75
 
76
+ ## Error behavior
77
+
78
+ - `errors`: high-level validation messages, capped by `max_errors` (default `20`).
79
+ - `issues`: detailed per-feature validation issues, also capped by `max_errors`.
80
+ - If null-like placeholders are found in feature `properties`, validation fails early before schema checks with actionable messages such as:
81
+ - `Invalid value at 'climb': 'null'. Null/NaN placeholders are not allowed; provide a valid value or remove this property.`
82
+ - For enum validation, long allowed-value lists are summarized as:
83
+ - first 5 values joined by `|`
84
+ - followed by `| and N more` when applicable.
85
+
74
86
  You can also override schemas:
75
87
 
76
88
  ```python
@@ -1,7 +1,7 @@
1
- python_osw_validation/__init__.py,sha256=kvbtnQc0YTV4DDfVlomCuV2sW_tLkvh58aIFF9cXo0I,24824
1
+ python_osw_validation/__init__.py,sha256=mi96GGJsxtv8gmz_SEJl-kD6WCyqa5nnRDEscy8PVIo,27360
2
2
  python_osw_validation/extracted_data_validator.py,sha256=gEGYLaM_QkK6NrrhVYmNx-jMaNHXC4PbDGf1zKwJre4,6605
3
- python_osw_validation/helpers.py,sha256=w8UdJlX4zdTDTMthvllyPa8yg8oOueaCZ07bCDeky30,3660
4
- python_osw_validation/version.py,sha256=snJxJpwiPJe6cPv4idDkwuskE-MSt5MKd_03pSWcN8A,22
3
+ python_osw_validation/helpers.py,sha256=_LgtNoFTjJLqg64zxJLO1Q4dPpui_lWNPNDMnqN8Qck,8106
4
+ python_osw_validation/version.py,sha256=MZROqMwVP4JA-LXfTOR7mgacQSXDOlHt1eBZRUHPRnc,22
5
5
  python_osw_validation/zipfile_handler.py,sha256=jXnP-8O5AAOBapuNF3-XdFVM1MHiPaWpl_wlbX-aqhY,2631
6
6
  python_osw_validation/schema/opensidewalks.edges.schema-0.3.json,sha256=Egp--i6ahiUDKY55g_fuv71HkVPtnQN5OW8L_okRa8o,79638
7
7
  python_osw_validation/schema/opensidewalks.lines.schema-0.3.json,sha256=3s-VXiMPv0_wv3yU2iGw8iKjE3Ec1w6QKkUsQURp2II,9470
@@ -10,8 +10,8 @@ python_osw_validation/schema/opensidewalks.points.schema-0.3.json,sha256=WYmlC4Q
10
10
  python_osw_validation/schema/opensidewalks.polygons.schema-0.3.json,sha256=VzDpHv1ZVT42cAk9n3gsFZjS7WcflQzSbjN-aNIVTYM,16286
11
11
  python_osw_validation/schema/opensidewalks.schema-0.3.json,sha256=vyyGzPpqLxr1e5wFfNKzlA1sr6tmhHKM7ntaTk8z5k8,278489
12
12
  python_osw_validation/schema/opensidewalks.zones.schema-0.3.json,sha256=JCqoCJj-dCuPVPHWSUQhRJMebaJ9IrzHWwTVAC6j7dY,11281
13
- python_osw_validation-0.3.5.dist-info/licenses/LICENSE,sha256=2bm9uFabQZ3Ykb_SaSU_uUbAj2-htc6WJQmS_65qD00,1073
14
- python_osw_validation-0.3.5.dist-info/METADATA,sha256=aesaqBf_PLLhnm62zzDTDji3DTAoPT0he7nKvCtgjI4,5256
15
- python_osw_validation-0.3.5.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91
16
- python_osw_validation-0.3.5.dist-info/top_level.txt,sha256=GE81UPcDHEffJCxYu3M_iPz3Dt-O3axB73R5SLm_Veo,22
17
- python_osw_validation-0.3.5.dist-info/RECORD,,
13
+ python_osw_validation-0.3.7.dist-info/licenses/LICENSE,sha256=2bm9uFabQZ3Ykb_SaSU_uUbAj2-htc6WJQmS_65qD00,1073
14
+ python_osw_validation-0.3.7.dist-info/METADATA,sha256=fIvHtskEIVWYAbvjCHTF0WaTOsMEjbWVMR4h2UYYNN8,6080
15
+ python_osw_validation-0.3.7.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91
16
+ python_osw_validation-0.3.7.dist-info/top_level.txt,sha256=GE81UPcDHEffJCxYu3M_iPz3Dt-O3axB73R5SLm_Veo,22
17
+ python_osw_validation-0.3.7.dist-info/RECORD,,