Elffuss BraidHub

kikocis/llama-stack public

main · 2.3 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7import re
8import textwrap
9
10from termcolor import cprint
11
12
13def strip_ansi_colors(text):
14 ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
15 return ansi_escape.sub("", text)
16
17
18def format_row(row, col_widths):
19 def wrap(text, width):
20 lines = []
21 for line in text.split("\n"):
22 if line.strip() == "":
23 lines.append("")
24 else:
25 lines.extend(
26 textwrap.wrap(
27 line, width, break_long_words=False, replace_whitespace=False
28 )
29 )
30 return lines
31
32 wrapped = [wrap(item, width) for item, width in zip(row, col_widths)]
33 max_lines = max(len(subrow) for subrow in wrapped)
34
35 lines = []
36 for i in range(max_lines):
37 line = []
38 for cell_lines, width in zip(wrapped, col_widths):
39 value = cell_lines[i] if i < len(cell_lines) else ""
40 line.append(value + " " * (width - len(strip_ansi_colors(value))))
41 lines.append("| " + (" | ".join(line)) + " |")
42
43 return "\n".join(lines)
44
45
46def print_table(rows, headers=None, separate_rows: bool = False):
47 def itemlen(item):
48 return max([len(line) for line in strip_ansi_colors(item).split("\n")])
49
50 rows = [[x or "" for x in row] for row in rows]
51 if not headers:
52 col_widths = [max(itemlen(item) for item in col) for col in zip(*rows)]
53 else:
54 col_widths = [
55 max(
56 itemlen(header),
57 max(itemlen(item) for item in col),
58 )
59 for header, col in zip(headers, zip(*rows))
60 ]
61 col_widths = [min(w, 80) for w in col_widths]
62
63 header_line = "+".join("-" * (width + 2) for width in col_widths)
64 header_line = f"+{header_line}+"
65
66 if headers:
67 print(header_line)
68 cprint(format_row(headers, col_widths), "white", attrs=["bold"])
69
70 print(header_line)
71 for row in rows:
72 print(format_row(row, col_widths))
73 if separate_rows:
74 print(header_line)
75
76 if not separate_rows:
77 print(header_line)