stac-validator 3.9.2__tar.gz → 3.10.0__tar.gz

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,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: stac_validator
3
- Version: 3.9.2
3
+ Version: 3.10.0
4
4
  Summary: A package to validate STAC files
5
5
  Home-page: https://github.com/stac-utils/stac-validator
6
6
  Author: James Banting, Jonathan Healy
@@ -26,7 +26,7 @@ License-File: LICENSE
26
26
  <img src="https://raw.githubusercontent.com/stac-utils/stac-validator/main/assets/stac-validator.png" width=560>
27
27
  </p>
28
28
 
29
- [![Downloads](https://static.pepy.tech/badge/stac-validator?color=blue)](https://pepy.tech/project/stac-validator)
29
+ [![PyPI Downloads](https://static.pepy.tech/badge/stac-validator/month)](https://pepy.tech/projects/stac-validator)
30
30
  [![GitHub contributors](https://img.shields.io/github/contributors/stac-utils/stac-validator?color=blue)](https://github.com/stac-utils/stac-validator/graphs/contributors)
31
31
  [![GitHub stars](https://img.shields.io/github/stars/stac-utils/stac-validator.svg?color=blue)](https://github.com/stac-utils/stac-validator/stargazers)
32
32
  [![GitHub forks](https://img.shields.io/github/forks/stac-utils/stac-validator.svg?color=blue)](https://github.com/stac-utils/stac-validator/network/members)
@@ -6,7 +6,7 @@
6
6
  <img src="https://raw.githubusercontent.com/stac-utils/stac-validator/main/assets/stac-validator.png" width=560>
7
7
  </p>
8
8
 
9
- [![Downloads](https://static.pepy.tech/badge/stac-validator?color=blue)](https://pepy.tech/project/stac-validator)
9
+ [![PyPI Downloads](https://static.pepy.tech/badge/stac-validator/month)](https://pepy.tech/projects/stac-validator)
10
10
  [![GitHub contributors](https://img.shields.io/github/contributors/stac-utils/stac-validator?color=blue)](https://github.com/stac-utils/stac-validator/graphs/contributors)
11
11
  [![GitHub stars](https://img.shields.io/github/stars/stac-utils/stac-validator.svg?color=blue)](https://github.com/stac-utils/stac-validator/stargazers)
12
12
  [![GitHub forks](https://img.shields.io/github/forks/stac-utils/stac-validator.svg?color=blue)](https://github.com/stac-utils/stac-validator/network/members)
@@ -2,7 +2,7 @@
2
2
 
3
3
  from setuptools import setup
4
4
 
5
- __version__ = "3.9.2"
5
+ __version__ = "3.10.0"
6
6
 
7
7
  with open("README.md", "r") as fh:
8
8
  long_description = fh.read()
@@ -1,5 +1,6 @@
1
1
  import json
2
2
  import sys
3
+ import time
3
4
  from typing import Any, Dict, List, Optional, Tuple
4
5
 
5
6
  import click # type: ignore
@@ -7,6 +8,45 @@ import click # type: ignore
7
8
  from .validate import StacValidate
8
9
 
9
10
 
11
+ def _print_summary(
12
+ title: str, valid_count: int, total_count: int, obj_type: str = "STAC objects"
13
+ ) -> None:
14
+ """Helper function to print a consistent summary line.
15
+
16
+ Args:
17
+ title (str): Title of the summary section
18
+ valid_count (int): Number of valid items
19
+ total_count (int): Total number of items
20
+ obj_type (str): Type of objects being counted (e.g., 'items', 'collections')
21
+ """
22
+ click.secho()
23
+ click.secho(f"{title}:", bold=True)
24
+ if total_count > 0:
25
+ percentage = (valid_count / total_count) * 100
26
+ click.secho(
27
+ f" {obj_type.capitalize()} passed: {valid_count}/{total_count} ({percentage:.1f}%)"
28
+ )
29
+ else:
30
+ click.secho(f" No {obj_type} found to validate")
31
+
32
+
33
+ def format_duration(seconds: float) -> str:
34
+ """Format duration in seconds to a human-readable string.
35
+
36
+ Args:
37
+ seconds (float): Duration in seconds
38
+
39
+ Returns:
40
+ str: Formatted duration string (e.g., '1m 23.45s' or '456.78ms')
41
+ """
42
+ if seconds < 1.0:
43
+ return f"{seconds * 1000:.2f}ms"
44
+ minutes, seconds = divmod(seconds, 60)
45
+ if minutes > 0:
46
+ return f"{int(minutes)}m {seconds:.2f}s"
47
+ return f"{seconds:.2f}s"
48
+
49
+
10
50
  def print_update_message(version: str) -> None:
11
51
  """Prints an update message for `stac-validator` based on the version of the
12
52
  STAC file being validated.
@@ -36,33 +76,64 @@ def item_collection_summary(message: List[Dict[str, Any]]) -> None:
36
76
  Returns:
37
77
  None
38
78
  """
39
- valid_count = 0
40
- for item in message:
41
- if "valid_stac" in item and item["valid_stac"] is True:
42
- valid_count = valid_count + 1
43
- click.secho()
44
- click.secho("--item-collection summary", bold=True)
45
- click.secho(f"items_validated: {len(message)}")
46
- click.secho(f"valid_items: {valid_count}")
79
+ valid_count = sum(1 for item in message if item.get("valid_stac") is True)
80
+ _print_summary("-- Item Collection Summary", valid_count, len(message), "items")
47
81
 
48
82
 
49
83
  def collections_summary(message: List[Dict[str, Any]]) -> None:
50
- """Prints a summary of the validation results for an item collection response.
84
+ """Prints a summary of the validation results for a collections response.
51
85
 
52
86
  Args:
53
- message (List[Dict[str, Any]]): The validation results for the item collection.
87
+ message (List[Dict[str, Any]]): The validation results for the collections.
54
88
 
55
89
  Returns:
56
90
  None
57
91
  """
58
- valid_count = 0
59
- for collection in message:
60
- if "valid_stac" in collection and collection["valid_stac"] is True:
61
- valid_count = valid_count + 1
62
- click.secho()
63
- click.secho("--collections summary", bold=True)
64
- click.secho(f"collections_validated: {len(message)}")
65
- click.secho(f"valid_collections: {valid_count}")
92
+ valid_count = sum(1 for coll in message if coll.get("valid_stac") is True)
93
+ _print_summary("-- Collections Summary", valid_count, len(message), "collections")
94
+
95
+
96
+ def recursive_validation_summary(message: List[Dict[str, Any]]) -> None:
97
+ """Prints a summary of the recursive validation results.
98
+
99
+ Args:
100
+ message (List[Dict[str, Any]]): The validation results from recursive validation.
101
+
102
+ Returns:
103
+ None
104
+ """
105
+ # Count valid and total objects by type
106
+ type_counts = {}
107
+ total_valid = 0
108
+
109
+ for item in message:
110
+ if not isinstance(item, dict):
111
+ continue
112
+
113
+ obj_type = item.get("asset_type", "unknown").lower()
114
+ is_valid = item.get("valid_stac", False) is True
115
+
116
+ if obj_type not in type_counts:
117
+ type_counts[obj_type] = {"valid": 0, "total": 0}
118
+
119
+ type_counts[obj_type]["total"] += 1
120
+ if is_valid:
121
+ type_counts[obj_type]["valid"] += 1
122
+ total_valid += 1
123
+
124
+ # Print overall summary
125
+ _print_summary("-- Recursive Validation Summary", total_valid, len(message))
126
+
127
+ # Print breakdown by type if there are multiple types
128
+ if len(type_counts) > 1:
129
+ click.secho("\n Breakdown by type:")
130
+ for obj_type, counts in sorted(type_counts.items()):
131
+ percentage = (
132
+ (counts["valid"] / counts["total"]) * 100 if counts["total"] > 0 else 0
133
+ )
134
+ click.secho(
135
+ f" {obj_type.capitalize()}: {counts['valid']}/{counts['total']} ({percentage:.1f}%)"
136
+ )
66
137
 
67
138
 
68
139
  @click.command()
@@ -182,7 +253,7 @@ def main(
182
253
  log_file: str,
183
254
  pydantic: bool,
184
255
  verbose: bool = False,
185
- ) -> None:
256
+ ):
186
257
  """Main function for the `stac-validator` command line tool. Validates a STAC file
187
258
  against the STAC specification and prints the validation results to the console as JSON.
188
259
 
@@ -190,7 +261,8 @@ def main(
190
261
  stac_file (str): Path to the STAC file to be validated.
191
262
  collections (bool): Validate response from /collections endpoint.
192
263
  item_collection (bool): Whether to validate item collection responses.
193
- no_assets_urls (bool): Whether to open href links when validating assets (enabled by default).
264
+ no_assets_urls (bool): Whether to open href links when validating assets
265
+ (enabled by default).
194
266
  headers (dict): HTTP headers to include in the requests.
195
267
  pages (int): Maximum number of pages to validate via `item_collection`.
196
268
  recursive (bool): Whether to recursively validate all related STAC objects.
@@ -215,11 +287,14 @@ def main(
215
287
  SystemExit: Exits the program with a status code of 0 if the STAC file is valid,
216
288
  or 1 if it is invalid.
217
289
  """
290
+ start_time = time.time()
218
291
  valid = True
292
+
219
293
  if schema_map == ():
220
294
  schema_map_dict: Optional[Dict[str, str]] = None
221
295
  else:
222
296
  schema_map_dict = dict(schema_map)
297
+
223
298
  stac = StacValidate(
224
299
  stac_file=stac_file,
225
300
  collections=collections,
@@ -241,25 +316,37 @@ def main(
241
316
  pydantic=pydantic,
242
317
  verbose=verbose,
243
318
  )
244
- if not item_collection and not collections:
245
- valid = stac.run()
246
- elif collections:
247
- stac.validate_collections()
248
- else:
249
- stac.validate_item_collection()
250
319
 
251
- message = stac.message
252
- if "version" in message[0]:
253
- print_update_message(message[0]["version"])
320
+ try:
321
+ if not item_collection and not collections:
322
+ valid = stac.run()
323
+ elif collections:
324
+ stac.validate_collections()
325
+ else:
326
+ stac.validate_item_collection()
327
+
328
+ message = stac.message
329
+ if "version" in message[0]:
330
+ print_update_message(message[0]["version"])
254
331
 
255
- if no_output is False:
256
- click.echo(json.dumps(message, indent=4))
332
+ if no_output is False:
333
+ click.echo(json.dumps(message, indent=4))
257
334
 
258
- if item_collection:
259
- item_collection_summary(message)
260
- elif collections:
261
- collections_summary(message)
335
+ # Print appropriate summary based on validation mode
336
+ if item_collection:
337
+ item_collection_summary(message)
338
+ elif collections:
339
+ collections_summary(message)
340
+ elif recursive:
341
+ recursive_validation_summary(message)
262
342
 
343
+ finally:
344
+ # Always print the duration, even if validation fails
345
+ duration = time.time() - start_time
346
+ click.secho(
347
+ f"\nValidation completed in {format_duration(duration)}", fg="green"
348
+ )
349
+ click.secho()
263
350
  sys.exit(0 if valid else 1)
264
351
 
265
352
 
@@ -242,7 +242,11 @@ class StacValidate:
242
242
  return str(error_input) # Fallback to string representation
243
243
 
244
244
  def create_err_msg(
245
- self, err_type: str, err_msg: str, error_obj: Optional[Exception] = None
245
+ self,
246
+ err_type: str,
247
+ err_msg: str,
248
+ error_obj: Optional[Exception] = None,
249
+ schema_uri: str = "",
246
250
  ) -> Dict[str, Union[str, bool, List[str], Dict[str, Any]]]:
247
251
  """
248
252
  Create a standardized error message dictionary and mark validation as failed.
@@ -251,6 +255,7 @@ class StacValidate:
251
255
  err_type (str): The type of error.
252
256
  err_msg (str): The error message.
253
257
  error_obj (Optional[Exception]): The raw exception object for verbose details.
258
+ schema_uri (str, optional): The URI of the schema that failed validation.
254
259
 
255
260
  Returns:
256
261
  dict: Dictionary containing error information.
@@ -258,8 +263,40 @@ class StacValidate:
258
263
  self.valid = False
259
264
 
260
265
  # Ensure all values are of the correct type
261
- version_str: str = str(self.version) if self.version is not None else ""
262
- path_str: str = str(self.stac_file) if self.stac_file is not None else ""
266
+ if not isinstance(err_type, str):
267
+ err_type = str(err_type)
268
+ if not isinstance(err_msg, str):
269
+ err_msg = str(err_msg)
270
+
271
+ # Initialize the message with common fields
272
+ message: Dict[str, Any] = {
273
+ "version": str(self.version) if hasattr(self, "version") else "",
274
+ "path": str(self.stac_file) if hasattr(self, "stac_file") else "",
275
+ "schema": (
276
+ [self._original_schema_paths.get(self.schema, self.schema)]
277
+ if hasattr(self, "schema")
278
+ else [""]
279
+ ),
280
+ "valid_stac": False,
281
+ "error_type": err_type,
282
+ "error_message": err_msg,
283
+ "failed_schema": schema_uri if schema_uri else "",
284
+ "recommendation": "For more accurate error information, rerun with --verbose.",
285
+ }
286
+
287
+ # Add asset_type and validation_method if available
288
+ if hasattr(self, "stac_content"):
289
+ try:
290
+ stac_type = get_stac_type(self.stac_content)
291
+ if stac_type:
292
+ message["asset_type"] = stac_type.upper()
293
+ message["validation_method"] = (
294
+ "recursive"
295
+ if hasattr(self, "recursive") and self.recursive
296
+ else "default"
297
+ )
298
+ except Exception: # noqa: BLE001
299
+ pass
263
300
 
264
301
  # Ensure schema is properly typed
265
302
  schema_value: str = ""
@@ -267,10 +304,10 @@ class StacValidate:
267
304
  schema_value = str(self.schema)
268
305
  schema_field: List[str] = [schema_value] if schema_value else []
269
306
 
270
- # Initialize the message with common fields
271
- message: Dict[str, Union[str, bool, List[str], Dict[str, Any]]] = {
272
- "version": version_str,
273
- "path": path_str,
307
+ # Initialize the error message with common fields
308
+ error_message: Dict[str, Union[str, bool, List[str], Dict[str, Any]]] = {
309
+ "version": str(self.version) if self.version is not None else "",
310
+ "path": str(self.stac_file) if self.stac_file is not None else "",
274
311
  "schema": schema_field, # All schemas that were checked
275
312
  "valid_stac": False,
276
313
  "error_type": err_type,
@@ -281,31 +318,31 @@ class StacValidate:
281
318
  # Try to extract the failed schema from the error message if it's a validation error
282
319
  if error_obj and hasattr(error_obj, "schema"):
283
320
  if isinstance(error_obj.schema, dict) and "$id" in error_obj.schema:
284
- message["failed_schema"] = error_obj.schema["$id"]
321
+ error_message["failed_schema"] = error_obj.schema["$id"]
285
322
  elif hasattr(error_obj, "schema_url"):
286
- message["failed_schema"] = error_obj.schema_url
323
+ error_message["failed_schema"] = error_obj.schema_url
287
324
  # If we can't find a schema ID, try to get it from the schema map
288
325
  elif schema_field and len(schema_field) == 1:
289
- message["failed_schema"] = schema_field[0]
326
+ error_message["failed_schema"] = schema_field[0]
290
327
 
291
328
  if self.verbose and error_obj is not None:
292
329
  verbose_err = self._create_verbose_err_msg(error_obj)
293
330
  if isinstance(verbose_err, dict):
294
- message["error_verbose"] = verbose_err
331
+ error_message["error_verbose"] = verbose_err
295
332
  else:
296
- message["error_verbose"] = {"detail": str(verbose_err)}
333
+ error_message["error_verbose"] = {"detail": str(verbose_err)}
297
334
  # Add recommendation to check the schema if the error is not clear
298
- if "failed_schema" in message and message["failed_schema"]:
299
- message["recommendation"] = (
335
+ if error_message.get("failed_schema"):
336
+ error_message["recommendation"] = (
300
337
  "If the error is unclear, please check the schema documentation at: "
301
- f"{message['failed_schema']}"
338
+ f"{error_message['failed_schema']}"
302
339
  )
303
340
  else:
304
- message["recommendation"] = (
341
+ error_message["recommendation"] = (
305
342
  "For more accurate error information, rerun with --verbose."
306
343
  )
307
344
 
308
- return message
345
+ return error_message
309
346
 
310
347
  def create_links_message(self) -> Dict:
311
348
  """
@@ -561,7 +598,8 @@ class StacValidate:
561
598
  """
562
599
  Recursively validate a STAC JSON document and its children/items.
563
600
 
564
- Follows "child" and "item" links, calling `default_validator` on each.
601
+ Follows "child" and "item" links, calling the appropriate validator on each.
602
+ Uses pydantic_validator if self.pydantic is True, otherwise uses default_validator.
565
603
 
566
604
  Args:
567
605
  stac_type (str): The STAC object type to validate.
@@ -574,10 +612,19 @@ class StacValidate:
574
612
  self.schema = set_schema_addr(self.version, stac_type.lower())
575
613
  message = self.create_message(stac_type, "recursive")
576
614
  message["valid_stac"] = False
615
+ # Add validator_engine field to track validation method
616
+ message["validator_engine"] = "pydantic" if self.pydantic else "jsonschema"
577
617
 
578
618
  try:
579
- msg = self.default_validator(stac_type)
580
- message["schema"] = msg["schema"]
619
+ if self.pydantic:
620
+ # Set pydantic model info in schema field
621
+ model_name = f"stac-pydantic {stac_type.capitalize()} model"
622
+ message["schema"] = [model_name]
623
+ # Run pydantic validation
624
+ msg = self.pydantic_validator(stac_type)
625
+ else:
626
+ msg = self.default_validator(stac_type)
627
+ message["schema"] = msg["schema"]
581
628
 
582
629
  except jsonschema.exceptions.ValidationError as e:
583
630
  if e.context:
@@ -594,12 +641,31 @@ class StacValidate:
594
641
  err_type="JSONSchemaValidationError",
595
642
  err_msg=err_msg,
596
643
  error_obj=e,
644
+ schema_uri=(
645
+ e.schema.get("$id", "")
646
+ if hasattr(e, "schema") and isinstance(e.schema, dict)
647
+ else ""
648
+ ),
597
649
  )
598
650
  )
599
651
  self.message.append(message)
600
652
  if self.trace_recursion:
601
653
  click.echo(json.dumps(message, indent=4))
602
654
  return valid
655
+ except Exception as e:
656
+ if self.pydantic and "pydantic" in str(e.__class__.__module__):
657
+ message.update(
658
+ self.create_err_msg(
659
+ err_type="PydanticValidationError",
660
+ err_msg=str(e),
661
+ error_obj=e,
662
+ )
663
+ )
664
+ self.message.append(message)
665
+ if self.trace_recursion:
666
+ click.echo(json.dumps(message, indent=4))
667
+ return valid
668
+ raise
603
669
 
604
670
  valid = True
605
671
  message["valid_stac"] = valid
@@ -618,12 +684,32 @@ class StacValidate:
618
684
  if link["rel"] in ("child", "item"):
619
685
  address = link["href"]
620
686
  if not is_valid_url(address):
621
- path_parts = str(base_url).split("/")
622
- path_parts.pop(-1)
623
- root = path_parts[0]
624
- for i in range(1, len(path_parts)):
625
- root = f"{root}/{path_parts[i]}"
626
- self.stac_file = f"{root}/{address}"
687
+ if is_valid_url(str(base_url)):
688
+ # If base is a URL, handle URL joining
689
+ from urllib.parse import urljoin
690
+
691
+ self.stac_file = urljoin(
692
+ (
693
+ str(base_url) + "/"
694
+ if not str(base_url).endswith("/")
695
+ else str(base_url)
696
+ ),
697
+ address,
698
+ )
699
+ else:
700
+ # Handle local file paths
701
+ current_dir = os.path.dirname(
702
+ os.path.abspath(str(base_url))
703
+ )
704
+ self.stac_file = os.path.normpath(
705
+ os.path.join(current_dir, address)
706
+ )
707
+ # Convert to relative path for cleaner output if it's under the current working directory
708
+ try:
709
+ self.stac_file = os.path.relpath(self.stac_file)
710
+ except ValueError:
711
+ # If paths are on different drives (Windows) or other relpath issues, use the absolute path
712
+ pass
627
713
  else:
628
714
  self.stac_file = address
629
715
 
@@ -641,19 +727,39 @@ class StacValidate:
641
727
  if link["rel"] == "item":
642
728
  self.schema = set_schema_addr(self.version, stac_type.lower())
643
729
  message = self.create_message(stac_type, "recursive")
644
- if self.version == "0.7.0":
645
- schema = fetch_and_parse_schema(self.schema)
646
- # Prevent unknown url type issue
647
- schema["allOf"] = [{}]
648
- jsonschema.validate(self.stac_content, schema)
649
- else:
650
- msg = self.default_validator(stac_type)
651
- message["schema"] = msg["schema"]
652
- message["valid_stac"] = True
730
+ message["validator_engine"] = (
731
+ "pydantic" if self.pydantic else "jsonschema"
732
+ )
733
+ try:
734
+ if self.pydantic:
735
+ # Set pydantic model info in schema field for child items
736
+ model_name = f"stac-pydantic {stac_type.capitalize()} model"
737
+ message["schema"] = [model_name]
738
+ # Run pydantic validation
739
+ msg = self.pydantic_validator(stac_type)
740
+ elif self.version == "0.7.0":
741
+ schema = fetch_and_parse_schema(self.schema)
742
+ # Prevent unknown url type issue
743
+ schema["allOf"] = [{}]
744
+ jsonschema.validate(self.stac_content, schema)
745
+ else:
746
+ msg = self.default_validator(stac_type)
747
+ message["schema"] = msg["schema"]
748
+ message["valid_stac"] = True
749
+ except Exception as e:
750
+ if self.pydantic and "pydantic" in str(e.__class__.__module__):
751
+ message.update(
752
+ self.create_err_msg(
753
+ err_type="PydanticValidationError",
754
+ err_msg=str(e),
755
+ error_obj=e,
756
+ )
757
+ )
758
+ message["valid_stac"] = False
759
+ else:
760
+ raise
653
761
 
654
- if self.log:
655
- self.message.append(message)
656
- if not self.max_depth or self.max_depth < 5:
762
+ if self.log or (not self.max_depth or self.max_depth < 5):
657
763
  self.message.append(message)
658
764
  if all(child_validity):
659
765
  valid = True
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: stac-validator
3
- Version: 3.9.2
3
+ Version: 3.10.0
4
4
  Summary: A package to validate STAC files
5
5
  Home-page: https://github.com/stac-utils/stac-validator
6
6
  Author: James Banting, Jonathan Healy
@@ -26,7 +26,7 @@ License-File: LICENSE
26
26
  <img src="https://raw.githubusercontent.com/stac-utils/stac-validator/main/assets/stac-validator.png" width=560>
27
27
  </p>
28
28
 
29
- [![Downloads](https://static.pepy.tech/badge/stac-validator?color=blue)](https://pepy.tech/project/stac-validator)
29
+ [![PyPI Downloads](https://static.pepy.tech/badge/stac-validator/month)](https://pepy.tech/projects/stac-validator)
30
30
  [![GitHub contributors](https://img.shields.io/github/contributors/stac-utils/stac-validator?color=blue)](https://github.com/stac-utils/stac-validator/graphs/contributors)
31
31
  [![GitHub stars](https://img.shields.io/github/stars/stac-utils/stac-validator.svg?color=blue)](https://github.com/stac-utils/stac-validator/stargazers)
32
32
  [![GitHub forks](https://img.shields.io/github/forks/stac-utils/stac-validator.svg?color=blue)](https://github.com/stac-utils/stac-validator/network/members)
File without changes