Spaces:
Sleeping
Sleeping
| from __future__ import annotations | |
| import json | |
| from typing import Any, Dict | |
| def to_jsonable(obj: Any) -> Any: | |
| """Safely convert pandas/numpy objects to JSON-able python types.""" | |
| try: | |
| import numpy as np | |
| import pandas as pd | |
| except Exception: | |
| np = None | |
| pd = None | |
| if pd is not None and isinstance(obj, pd.DataFrame): | |
| return obj.to_dict(orient="records") | |
| if pd is not None and isinstance(obj, pd.Series): | |
| return obj.to_dict() | |
| if np is not None and isinstance(obj, (np.integer,)): | |
| return int(obj) | |
| if np is not None and isinstance(obj, (np.floating,)): | |
| f = float(obj) | |
| if f != f: # NaN | |
| return None | |
| return f | |
| if isinstance(obj, (set,)): | |
| return list(obj) | |
| if isinstance(obj, (bytes, bytearray)): | |
| return obj.decode("utf-8", errors="ignore") | |
| return obj | |
| def dumps(d: Dict[str, Any]) -> str: | |
| return json.dumps(d, ensure_ascii=False, default=to_jsonable) | |