Spaces:
Runtime error
Runtime error
| """ | |
| Helpers for safely converting cached model outputs into plain Python numbers. | |
| """ | |
| from __future__ import annotations | |
| import ast | |
| import math | |
| from typing import Any | |
| def coerce_float(value: Any, default: float = 0.0) -> float: | |
| if value is None: | |
| return default | |
| if isinstance(value, (list, tuple)): | |
| if not value: | |
| return default | |
| return coerce_float(value[0], default=default) | |
| if hasattr(value, "tolist") and not isinstance(value, (str, bytes)): | |
| return coerce_float(value.tolist(), default=default) | |
| if isinstance(value, str): | |
| text = value.strip() | |
| if not text: | |
| return default | |
| if text.startswith('[') and text.endswith(']'): | |
| try: | |
| parsed = ast.literal_eval(text) | |
| except (SyntaxError, ValueError): | |
| parsed = text[1:-1].strip() | |
| return coerce_float(parsed, default=default) | |
| try: | |
| result = float(text) | |
| except ValueError: | |
| return default | |
| return result if math.isfinite(result) else default | |
| try: | |
| result = float(value) | |
| except (TypeError, ValueError): | |
| return default | |
| return result if math.isfinite(result) else default | |
| def coerce_int(value: Any, default: int = 0) -> int: | |
| return int(round(coerce_float(value, default=float(default)))) | |