-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformatters.py
More file actions
155 lines (133 loc) · 4.63 KB
/
formatters.py
File metadata and controls
155 lines (133 loc) · 4.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
"""
python/formatters.py - Value formatting and display functions
"""
import numpy as np
import pandas as pd
import json
from pathlib import Path, PurePath
from decimal import Decimal
from fractions import Fraction
from uuid import UUID
from collections import OrderedDict, defaultdict, Counter, deque
import re
def is_json_string(obj):
"""Check if a string contains valid JSON"""
if not isinstance(obj, str):
return False
try:
json.loads(obj)
return True
except:
return False
def format_value(obj, var_type):
"""Get string representation of variable value"""
try:
# NumPy arrays
if isinstance(obj, np.ndarray):
if obj.size <= 10:
return str(obj.tolist())
else:
return f"ndarray object of numpy module"
# PyTorch tensors
elif 'torch' in str(type(obj)) and hasattr(obj, 'shape'):
return f"Tensor{tuple(obj.shape)}"
# TensorFlow tensors
elif 'tensorflow' in str(type(obj)) and hasattr(obj, 'shape'):
return f"Tensor{tuple(obj.shape)}"
# JAX arrays
elif 'jax' in str(type(obj)) and hasattr(obj, 'shape'):
return f"Array{tuple(obj.shape)}"
# Pandas
elif isinstance(obj, pd.DataFrame):
cols = ', '.join(obj.columns.tolist())
return f"Column names: {cols}"
# Path objects
elif isinstance(obj, (Path, PurePath)):
return str(obj)
# UUID
elif isinstance(obj, UUID):
return str(obj)
# Decimal and Fraction
elif isinstance(obj, Decimal):
return str(obj)
elif isinstance(obj, Fraction):
return str(obj)
# Regex patterns
elif isinstance(obj, re.Pattern):
return f"Pattern: {obj.pattern}"
# Collections
elif isinstance(obj, deque):
if len(obj) <= 10:
return f"deque({list(obj)})"
else:
preview = list(obj)[:3]
return f"deque([{', '.join(map(str, preview))}, ...])"
elif isinstance(obj, Counter):
if len(obj) <= 5:
return str(dict(obj))
else:
return f"Counter with {len(obj)} items"
elif isinstance(obj, (OrderedDict, defaultdict)):
if len(obj) <= 5:
return str(dict(obj))
else:
return f"{type(obj).__name__} with {len(obj)} items"
# Lists and tuples
elif isinstance(obj, (list, tuple)):
if len(obj) <= 10:
return str(obj)
else:
preview = str(obj[:3])[:-1] + ', ...]'
return preview
# Dicts and sets
elif isinstance(obj, dict):
if len(obj) <= 5:
return str(obj)
else:
return f"dict with {len(obj)} items"
elif isinstance(obj, (set, frozenset)):
if len(obj) <= 5:
return str(obj)
else:
return f"{type(obj).__name__} with {len(obj)} items"
# Generators
elif hasattr(obj, '__next__') and hasattr(obj, '__iter__'):
return f"<generator object>"
# Memoryview
elif isinstance(obj, memoryview):
return f"<memory at {hex(id(obj))}>"
# Strings
elif isinstance(obj, str):
if len(obj) > 100:
return obj[:97] + '...'
return obj
# Basic types
elif isinstance(obj, (int, float, complex, bool)):
return str(obj)
# Exceptions
elif isinstance(obj, BaseException):
return f"{type(obj).__name__}: {str(obj)}"
# Default
else:
result = str(obj)
if len(result) > 100:
return result[:97] + '...'
return result
except Exception as e:
return f"<Error displaying value: {str(e)}>"
def get_item_size(item):
"""Get size of an item for detail view"""
if isinstance(item, (list, tuple, dict, set, frozenset, deque, Counter, OrderedDict, defaultdict)):
return str(len(item))
elif isinstance(item, np.ndarray):
return str(item.shape)
elif 'torch' in str(type(item)) and hasattr(item, 'shape'):
return str(tuple(item.shape))
elif 'tensorflow' in str(type(item)) and hasattr(item, 'shape'):
return str(tuple(item.shape))
elif 'jax' in str(type(item)) and hasattr(item, 'shape'):
return str(tuple(item.shape))
elif isinstance(item, pd.DataFrame):
return f"({item.shape[0]}, {item.shape[1]})"
else:
return '1'