|
3 | 3 | import json |
4 | 4 | import os |
5 | 5 | from collections.abc import Mapping |
6 | | -from typing import Any |
| 6 | +from typing import TYPE_CHECKING, Any |
7 | 7 | from urllib.parse import urlparse |
8 | 8 |
|
9 | 9 | import s3fs |
|
13 | 13 |
|
14 | 14 | from eopf_geozarr.types import S3Credentials, S3FsOptions |
15 | 15 |
|
| 16 | +if TYPE_CHECKING: |
| 17 | + import xarray as xr |
| 18 | + |
| 19 | + |
| 20 | +def replace_json_invalid_floats(obj: object) -> object: |
| 21 | + """ |
| 22 | + Recursively replace NaN and Infinity float values in a JSON-like object |
| 23 | + with their string representations, to make them JSON-compliant. |
| 24 | +
|
| 25 | + Parameters |
| 26 | + ---------- |
| 27 | + obj : object |
| 28 | + The JSON-like object to process |
| 29 | +
|
| 30 | + Returns |
| 31 | + ------- |
| 32 | + object |
| 33 | + The processed object with NaN and Infinity replaced |
| 34 | + """ |
| 35 | + if isinstance(obj, float): |
| 36 | + if obj != obj: # NaN check |
| 37 | + return "NaN" |
| 38 | + if obj == float("inf"): |
| 39 | + return "Infinity" |
| 40 | + if obj == float("-inf"): |
| 41 | + return "-Infinity" |
| 42 | + return obj |
| 43 | + if isinstance(obj, dict): |
| 44 | + return {k: replace_json_invalid_floats(v) for k, v in obj.items()} |
| 45 | + if isinstance(obj, list): |
| 46 | + return [replace_json_invalid_floats(item) for item in obj] |
| 47 | + if isinstance(obj, tuple): |
| 48 | + return tuple(replace_json_invalid_floats(item) for item in obj) |
| 49 | + |
| 50 | + return obj |
| 51 | + |
| 52 | + |
| 53 | +class NanCompatibleJSONEncoder(json.JSONEncoder): |
| 54 | + """ |
| 55 | + Custom JSON encoder that converts NaN, Inf, -Inf values to JSON-safe equivalents |
| 56 | + to ensure valid JSON output. |
| 57 | + """ |
| 58 | + |
| 59 | + def encode(self, obj: Any) -> str: |
| 60 | + """ |
| 61 | + Encode object to JSON string, converting NaN values to "NaN". |
| 62 | + """ |
| 63 | + |
| 64 | + converted_obj = replace_json_invalid_floats(obj) |
| 65 | + return super().encode(converted_obj) |
| 66 | + |
| 67 | + |
| 68 | +def sanitize_dataset_attributes(ds: "xr.Dataset") -> "xr.Dataset": |
| 69 | + """ |
| 70 | + Sanitize all NaN values in a dataset's attributes, variable attributes, |
| 71 | + and coordinate attributes, converting them to "NaN" strings. |
| 72 | +
|
| 73 | + Parameters |
| 74 | + ---------- |
| 75 | + ds : xr.Dataset |
| 76 | + Dataset to sanitize |
| 77 | +
|
| 78 | + Returns |
| 79 | + ------- |
| 80 | + xr.Dataset |
| 81 | + Dataset with sanitized attributes |
| 82 | + """ |
| 83 | + |
| 84 | + # Create a copy to avoid modifying the original |
| 85 | + ds_clean = ds.copy() |
| 86 | + |
| 87 | + # Sanitize dataset attributes |
| 88 | + ds_clean.attrs = replace_json_invalid_floats(ds_clean.attrs) |
| 89 | + |
| 90 | + # Sanitize variable attributes |
| 91 | + for var_name in ds_clean.data_vars: |
| 92 | + var = ds_clean[var_name] |
| 93 | + var.attrs = replace_json_invalid_floats(var.attrs) |
| 94 | + |
| 95 | + # Sanitize coordinate attributes |
| 96 | + for coord_name in ds_clean.coords: |
| 97 | + coord = ds_clean[coord_name] |
| 98 | + coord.attrs = replace_json_invalid_floats(coord.attrs) |
| 99 | + |
| 100 | + return ds_clean |
| 101 | + |
16 | 102 |
|
17 | 103 | def normalize_s3_path(s3_path: str) -> str: |
18 | 104 | """ |
@@ -210,7 +296,7 @@ def write_s3_json_metadata(s3_path: str, metadata: Mapping[str, Any], **s3_kwarg |
210 | 296 | fs = s3fs.S3FileSystem(**s3_config) |
211 | 297 |
|
212 | 298 | # Write JSON content |
213 | | - json_content = json.dumps(metadata, indent=2) |
| 299 | + json_content = json.dumps(metadata, indent=2, cls=NanCompatibleJSONEncoder) |
214 | 300 | with fs.open(s3_path, "w") as f: |
215 | 301 | f.write(json_content) |
216 | 302 |
|
@@ -426,7 +512,7 @@ def write_json_metadata(path: str, metadata: dict[str, Any], **kwargs: Any) -> N |
426 | 512 | fs.makedirs(parent_dir, exist_ok=True) |
427 | 513 |
|
428 | 514 | # Write JSON content using fsspec |
429 | | - json_content = json.dumps(metadata, indent=2) |
| 515 | + json_content = json.dumps(metadata, indent=2, cls=NanCompatibleJSONEncoder) |
430 | 516 | with fs.open(path, "w") as f: |
431 | 517 | f.write(json_content) |
432 | 518 |
|
|
0 commit comments