Spaces:
Sleeping
Sleeping
| # Copyright (c) 2025-2026, RTE (https://www.rte-france.com) | |
| # This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0. | |
| # If a copy of the Mozilla Public License, version 2.0 was not distributed with this file, | |
| # you can obtain one at http://mozilla.org/MPL/2.0/. | |
| # SPDX-License-Identifier: MPL-2.0 | |
| # This file is part of Co-Study4Grid a Power Grid Study tool Assistant Interface to help solve contigencies for a grid state under study. | |
| """JSON sanitization utility for numpy/grid2op objects.""" | |
| from typing import Any | |
| import numpy as np | |
| def sanitize_for_json(obj: Any) -> Any: | |
| if isinstance(obj, bool): | |
| return obj | |
| if isinstance(obj, (np.integer, int)): | |
| return int(obj) | |
| elif isinstance(obj, (np.floating, float)): | |
| if np.isnan(obj) or np.isinf(obj): | |
| return None | |
| return float(obj) | |
| elif isinstance(obj, np.ndarray): | |
| return sanitize_for_json(obj.tolist()) | |
| elif isinstance(obj, dict): | |
| return {str(k): sanitize_for_json(v) for k, v in obj.items()} | |
| elif isinstance(obj, (list, tuple)): | |
| return [sanitize_for_json(i) for i in obj] | |
| elif isinstance(obj, (str, bool, type(None))): | |
| return obj | |
| else: | |
| # Fallback for unknown objects | |
| try: | |
| if hasattr(obj, "to_dict"): | |
| d = obj.to_dict() | |
| if isinstance(d, dict): | |
| return sanitize_for_json(d) | |
| return str(obj) | |
| return sanitize_for_json(vars(obj)) | |
| except (TypeError, ValueError): | |
| return str(obj) | |