Spaces:
Sleeping
Sleeping
Download app/core/utils.py from Ba7ath-Project/ahlya: direct link, hf CLI and curl.
- Browser
- Download file 1.35 kB
-
https://huggingface.co/spaces/Ba7ath-Project/ahlya/resolve/main/app/core/utils.py
- Command line
-
hf download hf://spaces/Ba7ath-Project/ahlya/app/core/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/Ba7ath-Project/ahlya/resolve/main/app/core/utils.py
1.35 kB
| import math | |
| from decimal import Decimal | |
| from typing import Any | |
| def clean_nans(obj: Any) -> Any: | |
| """ | |
| Recursive utility to replace NaN, Infinity, and -Infinity with None | |
| to ensure JSON compatibility. | |
| Standards Moez Elbey: Missing data => null/None. | |
| """ | |
| if isinstance(obj, float): | |
| if math.isnan(obj) or math.isinf(obj): | |
| return None | |
| return obj | |
| elif isinstance(obj, Decimal): | |
| return float(obj) | |
| elif isinstance(obj, dict): | |
| return {k: clean_nans(v) for k, v in obj.items()} | |
| elif isinstance(obj, list): | |
| return [clean_nans(v) for v in obj] | |
| return obj | |
| def safe_float(val: Any, default: float = 0.0) -> float: | |
| """Safely convert any value to float.""" | |
| try: | |
| if val is None or (isinstance(val, float) and math.isnan(val)): | |
| return default | |
| return float(val) | |
| except (ValueError, TypeError): | |
| return default | |
| def safe_int(val: Any, default: int = 0) -> int: | |
| """Safely convert any value to int.""" | |
| try: | |
| if val is None or (isinstance(val, float) and math.isnan(val)): | |
| return default | |
| return int(float(val)) | |
| except (ValueError, TypeError): | |
| return default | |
| def safe_list(val: Any) -> list: | |
| """Ensure value is a list.""" | |
| if isinstance(val, list): | |
| return val | |
| return [] | |