Recursively convert object to string.
Source code in SaigeToolkit/util/test.py
| def to_string(obj, indent=4, depth=0):
"""Recursively convert object to string."""
if isinstance(obj, Dict) and obj:
string = "{" + "\n"
for k, v in obj.items():
if k in ["polygon"]:
k = f"{k} (mid point)"
v = list(np.mean(np.array(v), axis=-2))
elif k in ["topk_sparse_matrix"]:
k = f"{k} (mean value)"
v = np.mean(v)
string += " " * indent * (depth + 1) + f'"{k}": ' + to_string(v, depth=depth + 1) + ",\n"
string += " " * indent * depth + "}"
elif isinstance(obj, List) and obj:
string = "[" + "\n"
string += " " * indent * (depth + 1) + to_string(obj[0], depth=depth + 1) + ",\n"
string += " " * indent * (depth + 1) + f"... # {len(obj) - 1} results,\n"
string += " " * indent * depth + "]"
elif isinstance(obj, Tuple) and obj:
string = "(" + "\n"
for v in obj:
string += " " * indent * (depth + 1) + to_string(v, depth=depth + 1) + ",\n"
string += " " * indent * depth + ")"
elif isinstance(obj, (np.ndarray, torch.Tensor)):
string = f"{type(obj).__name__}({obj.dtype}, shape={obj.shape}, min={obj.min().item()}, max={obj.max().item()})"
elif isinstance(obj, str):
string = f'"{obj}"' + f" ({type(obj).__name__})"
else:
string = f"{str(obj)} ({type(obj).__name__})"
return string
|