Spaces:
Running
Running
Update mew_log/table_utils.py
Browse files- mew_log/table_utils.py +174 -174
mew_log/table_utils.py
CHANGED
@@ -1,174 +1,174 @@
|
|
1 |
-
from tabulate import tabulate
|
2 |
-
|
3 |
-
from
|
4 |
-
from
|
5 |
-
|
6 |
-
|
7 |
-
def transpose_dict(d):
|
8 |
-
return {k: [dic[k] for dic in d.values()] for k in d.keys()}
|
9 |
-
|
10 |
-
|
11 |
-
def format_data_as_table(data, headers=None, tablefmt='grid', **kwargs):
|
12 |
-
if kwargs.get('use_color', False):
|
13 |
-
# Apply color to headers if applicable
|
14 |
-
if headers:
|
15 |
-
headers = [ansi_color_str(header, fg="yellow") for header in headers]
|
16 |
-
|
17 |
-
|
18 |
-
return tabulate(data, headers=headers, tablefmt=tablefmt)
|
19 |
-
|
20 |
-
def format_property(name, data, headers=None, tablefmt='simple_grid', use_color=False):
|
21 |
-
colored_name = ansi_color_str(f"===[{name}]<{type(data).__name__}>===", fg="yellow") if use_color else f"===[{name}]<{type(data).__name__}>==="
|
22 |
-
return f'{colored_name}\n{format_table(data, headers, tablefmt, use_color=use_color)}'
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
# note: pretty sure transpose doesn't work correctly
|
27 |
-
def format_table(data, headers=None, tablefmt='simple_grid', **kwargs):
|
28 |
-
if not data:
|
29 |
-
return ""
|
30 |
-
if isinstance(data, dict):
|
31 |
-
return format_dict_as_table(data, headers, tablefmt, **kwargs)
|
32 |
-
elif isinstance(data, (list, set)):
|
33 |
-
# transpose = list(zip(*data))
|
34 |
-
return format_list_as_table(data, headers, tablefmt, **kwargs)
|
35 |
-
elif hasattr(data, '__dict__'):
|
36 |
-
return format_obj_as_table(data, headers, tablefmt, **kwargs)
|
37 |
-
else:
|
38 |
-
use_color = kwargs.get('use_color', False)
|
39 |
-
if use_color:
|
40 |
-
return ansi_color_str(str(data), fg='bright_yellow')
|
41 |
-
else:
|
42 |
-
return str(data)
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
def format_list_as_table(data, headers=None, tablefmt='simple', **kwargs):
|
47 |
-
if not headers:
|
48 |
-
headers = ["Index", "Value"] if kwargs.get('show_indexes', False) else []
|
49 |
-
|
50 |
-
if kwargs.get('show_indexes', False):
|
51 |
-
out_dict = {i: item for i, item in enumerate(data)}
|
52 |
-
return format_table(out_dict, headers, tablefmt, **kwargs)
|
53 |
-
else:
|
54 |
-
formatted_str = ansi_color_str(f" | len={len(data)} | ", fg='bright_cyan') if kwargs.get('use_color', False) else f" | len={len(data)} | "
|
55 |
-
formatted_str += "["
|
56 |
-
for i, item in enumerate(data):
|
57 |
-
formatted_str += format_table(item, [], tablefmt, **kwargs)
|
58 |
-
if i < len(data) - 1: formatted_str += kwargs.get('delimeter', ', ')
|
59 |
-
formatted_str += "]"
|
60 |
-
return formatted_str
|
61 |
-
|
62 |
-
|
63 |
-
def format_dict_as_table(data, headers=None, tablefmt='simple_grid', **kwargs):
|
64 |
-
if kwargs.get('transpose', False):
|
65 |
-
if not headers:
|
66 |
-
headers =list(data.keys())
|
67 |
-
#Transpose the dictionary: each key-value pair becomes a column
|
68 |
-
transposed_data = [list(value) for key, value in zip(list(data.keys()), zip(*data.items()))]
|
69 |
-
#intended for values of the same lenth
|
70 |
-
#transposed_data = [headers] + [list(row) for row in zip(list(data.values()))]
|
71 |
-
return format_data_as_table(transposed_data, headers=headers, tablefmt=tablefmt)
|
72 |
-
else:
|
73 |
-
if not headers:
|
74 |
-
headers = ["Key", "Value"]
|
75 |
-
|
76 |
-
# Convert the dictionary into a list of lists
|
77 |
-
table_data = [[key, format_table(value, [], 'simple',**kwargs)] for key, value in data.items() if value is not None]
|
78 |
-
|
79 |
-
# Format the table
|
80 |
-
return format_data_as_table(table_data, headers=headers, tablefmt=tablefmt)
|
81 |
-
|
82 |
-
|
83 |
-
def format_obj_as_table(data, headers=None, tablefmt='fancy_grid', **kwargs):
|
84 |
-
verbose = kwargs.get('verbose', True)
|
85 |
-
fancy = kwargs.get('fancy', True)
|
86 |
-
use_color = kwargs.get('use_color', True)
|
87 |
-
|
88 |
-
attributes_dict = get_class_attributes(data, verbose=verbose)
|
89 |
-
class_name = data.__class__.__name__
|
90 |
-
variables = [*attributes_dict['variables'].values()]
|
91 |
-
methods = [*attributes_dict['methods'].values()]
|
92 |
-
# Check if headers are provided, if not, construct them
|
93 |
-
if not headers:
|
94 |
-
headers = [class_name]
|
95 |
-
if variables:
|
96 |
-
headers.append('variables')
|
97 |
-
if methods:
|
98 |
-
headers.append('methods')
|
99 |
-
|
100 |
-
# Initialize an empty list to store the formatted table data
|
101 |
-
table_data = []
|
102 |
-
|
103 |
-
# formatted_vars = []
|
104 |
-
# for v in variables:
|
105 |
-
# format_v = format_arg(v, use_color=use_color, fancy=fancy)
|
106 |
-
# formatted_vars.append(format_v)
|
107 |
-
|
108 |
-
# Add variables and methods data to the table data
|
109 |
-
table_data.append([format_table(variables, ['variables'], 'simple', **kwargs) if variables else None,
|
110 |
-
format_table(methods, ['methods'], 'simple', **kwargs) if methods else None])
|
111 |
-
|
112 |
-
table_data = list(zip(*table_data))
|
113 |
-
|
114 |
-
# Return the formatted table
|
115 |
-
return format_data_as_table(table_data, headers, tablefmt, **kwargs)
|
116 |
-
|
117 |
-
|
118 |
-
def print_table(msg, data, headers=None, tablefmt='fancy_grid'):
|
119 |
-
print(f'==={msg}==>\n{format_table(data, headers, tablefmt)}')
|
120 |
-
|
121 |
-
|
122 |
-
def format_square_layout(data):
|
123 |
-
if isinstance(data, (list, set)):
|
124 |
-
result_count = len(data)
|
125 |
-
rows, columns = calc_best_square(result_count)
|
126 |
-
table_data = [data[i:i + columns] for i in range(0, len(data), columns)]
|
127 |
-
return format_table(table_data)
|
128 |
-
elif isinstance(data, dict):
|
129 |
-
items = [(k, v) for k, v in data.items()]
|
130 |
-
result_count = len(items)
|
131 |
-
rows, columns = calc_best_square(result_count)
|
132 |
-
table_data = [items[i:i + columns] for i in range(0, len(items), columns)]
|
133 |
-
return format_table(table_data)
|
134 |
-
elif hasattr(data, '__dict__'):
|
135 |
-
items = [(k, v) for k, v in data.__dict__.items()]
|
136 |
-
result_count = len(items)
|
137 |
-
rows, columns = calc_best_square(result_count)
|
138 |
-
table_data = [items[i:i + columns] for i in range(0, len(items), columns)]
|
139 |
-
return format_table(table_data)
|
140 |
-
else:
|
141 |
-
return format_table(data)
|
142 |
-
|
143 |
-
|
144 |
-
def print_square_layout(msg, data):
|
145 |
-
print(f'==={msg}==>\n{format_square_layout(data)}')
|
146 |
-
|
147 |
-
|
148 |
-
def print_as_square(strings):
|
149 |
-
# Calculate the number of strings in the input list
|
150 |
-
result_count = len(strings)
|
151 |
-
|
152 |
-
# Calculate the best square layout dimensions based on the result count
|
153 |
-
rows, columns = calc_best_square(result_count)
|
154 |
-
|
155 |
-
# Create a grid with empty strings filled in for each cell
|
156 |
-
grid = [[' ' for _ in range(columns)] for _ in range(rows)]
|
157 |
-
|
158 |
-
# Iterate over the strings and populate the grid with them
|
159 |
-
for i, string in enumerate(strings):
|
160 |
-
# Calculate the row and column index for the current string
|
161 |
-
row = i // columns
|
162 |
-
col = i % columns
|
163 |
-
# Ensure the row and column indices are within the valid range of the grid dimensions
|
164 |
-
if row < rows and col < columns:
|
165 |
-
# Place the string in the corresponding cell of the grid
|
166 |
-
grid[row][col] = string
|
167 |
-
|
168 |
-
# Determine the maximum width of each column in the grid
|
169 |
-
max_widths = [max(len(cell) for cell in row) for row in grid]
|
170 |
-
|
171 |
-
# Print the grid, ensuring each cell is left-aligned and padded to its maximum width
|
172 |
-
for row in grid:
|
173 |
-
print(' '.join(cell.ljust(width) for cell, width in zip(row, max_widths)))
|
174 |
-
|
|
|
1 |
+
from tabulate import tabulate
|
2 |
+
|
3 |
+
from ansi_utils import ansi_color_str
|
4 |
+
from attr_utils import get_class_attributes
|
5 |
+
|
6 |
+
|
7 |
+
def transpose_dict(d):
|
8 |
+
return {k: [dic[k] for dic in d.values()] for k in d.keys()}
|
9 |
+
|
10 |
+
|
11 |
+
def format_data_as_table(data, headers=None, tablefmt='grid', **kwargs):
|
12 |
+
if kwargs.get('use_color', False):
|
13 |
+
# Apply color to headers if applicable
|
14 |
+
if headers:
|
15 |
+
headers = [ansi_color_str(header, fg="yellow") for header in headers]
|
16 |
+
|
17 |
+
|
18 |
+
return tabulate(data, headers=headers, tablefmt=tablefmt)
|
19 |
+
|
20 |
+
def format_property(name, data, headers=None, tablefmt='simple_grid', use_color=False):
|
21 |
+
colored_name = ansi_color_str(f"===[{name}]<{type(data).__name__}>===", fg="yellow") if use_color else f"===[{name}]<{type(data).__name__}>==="
|
22 |
+
return f'{colored_name}\n{format_table(data, headers, tablefmt, use_color=use_color)}'
|
23 |
+
|
24 |
+
|
25 |
+
|
26 |
+
# note: pretty sure transpose doesn't work correctly
|
27 |
+
def format_table(data, headers=None, tablefmt='simple_grid', **kwargs):
|
28 |
+
if not data:
|
29 |
+
return ""
|
30 |
+
if isinstance(data, dict):
|
31 |
+
return format_dict_as_table(data, headers, tablefmt, **kwargs)
|
32 |
+
elif isinstance(data, (list, set)):
|
33 |
+
# transpose = list(zip(*data))
|
34 |
+
return format_list_as_table(data, headers, tablefmt, **kwargs)
|
35 |
+
elif hasattr(data, '__dict__'):
|
36 |
+
return format_obj_as_table(data, headers, tablefmt, **kwargs)
|
37 |
+
else:
|
38 |
+
use_color = kwargs.get('use_color', False)
|
39 |
+
if use_color:
|
40 |
+
return ansi_color_str(str(data), fg='bright_yellow')
|
41 |
+
else:
|
42 |
+
return str(data)
|
43 |
+
|
44 |
+
|
45 |
+
|
46 |
+
def format_list_as_table(data, headers=None, tablefmt='simple', **kwargs):
|
47 |
+
if not headers:
|
48 |
+
headers = ["Index", "Value"] if kwargs.get('show_indexes', False) else []
|
49 |
+
|
50 |
+
if kwargs.get('show_indexes', False):
|
51 |
+
out_dict = {i: item for i, item in enumerate(data)}
|
52 |
+
return format_table(out_dict, headers, tablefmt, **kwargs)
|
53 |
+
else:
|
54 |
+
formatted_str = ansi_color_str(f" | len={len(data)} | ", fg='bright_cyan') if kwargs.get('use_color', False) else f" | len={len(data)} | "
|
55 |
+
formatted_str += "["
|
56 |
+
for i, item in enumerate(data):
|
57 |
+
formatted_str += format_table(item, [], tablefmt, **kwargs)
|
58 |
+
if i < len(data) - 1: formatted_str += kwargs.get('delimeter', ', ')
|
59 |
+
formatted_str += "]"
|
60 |
+
return formatted_str
|
61 |
+
|
62 |
+
|
63 |
+
def format_dict_as_table(data, headers=None, tablefmt='simple_grid', **kwargs):
|
64 |
+
if kwargs.get('transpose', False):
|
65 |
+
if not headers:
|
66 |
+
headers =list(data.keys())
|
67 |
+
#Transpose the dictionary: each key-value pair becomes a column
|
68 |
+
transposed_data = [list(value) for key, value in zip(list(data.keys()), zip(*data.items()))]
|
69 |
+
#intended for values of the same lenth
|
70 |
+
#transposed_data = [headers] + [list(row) for row in zip(list(data.values()))]
|
71 |
+
return format_data_as_table(transposed_data, headers=headers, tablefmt=tablefmt)
|
72 |
+
else:
|
73 |
+
if not headers:
|
74 |
+
headers = ["Key", "Value"]
|
75 |
+
|
76 |
+
# Convert the dictionary into a list of lists
|
77 |
+
table_data = [[key, format_table(value, [], 'simple',**kwargs)] for key, value in data.items() if value is not None]
|
78 |
+
|
79 |
+
# Format the table
|
80 |
+
return format_data_as_table(table_data, headers=headers, tablefmt=tablefmt)
|
81 |
+
|
82 |
+
|
83 |
+
def format_obj_as_table(data, headers=None, tablefmt='fancy_grid', **kwargs):
|
84 |
+
verbose = kwargs.get('verbose', True)
|
85 |
+
fancy = kwargs.get('fancy', True)
|
86 |
+
use_color = kwargs.get('use_color', True)
|
87 |
+
|
88 |
+
attributes_dict = get_class_attributes(data, verbose=verbose)
|
89 |
+
class_name = data.__class__.__name__
|
90 |
+
variables = [*attributes_dict['variables'].values()]
|
91 |
+
methods = [*attributes_dict['methods'].values()]
|
92 |
+
# Check if headers are provided, if not, construct them
|
93 |
+
if not headers:
|
94 |
+
headers = [class_name]
|
95 |
+
if variables:
|
96 |
+
headers.append('variables')
|
97 |
+
if methods:
|
98 |
+
headers.append('methods')
|
99 |
+
|
100 |
+
# Initialize an empty list to store the formatted table data
|
101 |
+
table_data = []
|
102 |
+
|
103 |
+
# formatted_vars = []
|
104 |
+
# for v in variables:
|
105 |
+
# format_v = format_arg(v, use_color=use_color, fancy=fancy)
|
106 |
+
# formatted_vars.append(format_v)
|
107 |
+
|
108 |
+
# Add variables and methods data to the table data
|
109 |
+
table_data.append([format_table(variables, ['variables'], 'simple', **kwargs) if variables else None,
|
110 |
+
format_table(methods, ['methods'], 'simple', **kwargs) if methods else None])
|
111 |
+
|
112 |
+
table_data = list(zip(*table_data))
|
113 |
+
|
114 |
+
# Return the formatted table
|
115 |
+
return format_data_as_table(table_data, headers, tablefmt, **kwargs)
|
116 |
+
|
117 |
+
|
118 |
+
def print_table(msg, data, headers=None, tablefmt='fancy_grid'):
|
119 |
+
print(f'==={msg}==>\n{format_table(data, headers, tablefmt)}')
|
120 |
+
|
121 |
+
|
122 |
+
def format_square_layout(data):
|
123 |
+
if isinstance(data, (list, set)):
|
124 |
+
result_count = len(data)
|
125 |
+
rows, columns = calc_best_square(result_count)
|
126 |
+
table_data = [data[i:i + columns] for i in range(0, len(data), columns)]
|
127 |
+
return format_table(table_data)
|
128 |
+
elif isinstance(data, dict):
|
129 |
+
items = [(k, v) for k, v in data.items()]
|
130 |
+
result_count = len(items)
|
131 |
+
rows, columns = calc_best_square(result_count)
|
132 |
+
table_data = [items[i:i + columns] for i in range(0, len(items), columns)]
|
133 |
+
return format_table(table_data)
|
134 |
+
elif hasattr(data, '__dict__'):
|
135 |
+
items = [(k, v) for k, v in data.__dict__.items()]
|
136 |
+
result_count = len(items)
|
137 |
+
rows, columns = calc_best_square(result_count)
|
138 |
+
table_data = [items[i:i + columns] for i in range(0, len(items), columns)]
|
139 |
+
return format_table(table_data)
|
140 |
+
else:
|
141 |
+
return format_table(data)
|
142 |
+
|
143 |
+
|
144 |
+
def print_square_layout(msg, data):
|
145 |
+
print(f'==={msg}==>\n{format_square_layout(data)}')
|
146 |
+
|
147 |
+
|
148 |
+
def print_as_square(strings):
|
149 |
+
# Calculate the number of strings in the input list
|
150 |
+
result_count = len(strings)
|
151 |
+
|
152 |
+
# Calculate the best square layout dimensions based on the result count
|
153 |
+
rows, columns = calc_best_square(result_count)
|
154 |
+
|
155 |
+
# Create a grid with empty strings filled in for each cell
|
156 |
+
grid = [[' ' for _ in range(columns)] for _ in range(rows)]
|
157 |
+
|
158 |
+
# Iterate over the strings and populate the grid with them
|
159 |
+
for i, string in enumerate(strings):
|
160 |
+
# Calculate the row and column index for the current string
|
161 |
+
row = i // columns
|
162 |
+
col = i % columns
|
163 |
+
# Ensure the row and column indices are within the valid range of the grid dimensions
|
164 |
+
if row < rows and col < columns:
|
165 |
+
# Place the string in the corresponding cell of the grid
|
166 |
+
grid[row][col] = string
|
167 |
+
|
168 |
+
# Determine the maximum width of each column in the grid
|
169 |
+
max_widths = [max(len(cell) for cell in row) for row in grid]
|
170 |
+
|
171 |
+
# Print the grid, ensuring each cell is left-aligned and padded to its maximum width
|
172 |
+
for row in grid:
|
173 |
+
print(' '.join(cell.ljust(width) for cell, width in zip(row, max_widths)))
|
174 |
+
|