def draw_graphviz(G: dict[Any, dict | list], png_filename: Optional[str] = None, n=None, directed: bool = False, show_weights: bool = False, colours: dict[Any, str] | list[str] | Optional[str] = None, labels: dict[Any, Any] | list[Any] | Optional[str] = None) -> None:
"""Draw G as a picture in the terminal.
`colours` fills node i with colours[i]: a colour name, or one of the
letters RGBYWMCK as a LeetCode colours string spells them.
`labels` writes labels[i] under the name of node i.
Both take a dict, a list or a string, indexed by node."""
if os.environ.get("RUNNING_TESTS") == "True":
return
G = as_dict_of_dicts(build_graph_from_edge_list(G, directed) if is_edge_list(G) else G)
if png_filename is None:
sorted_G = Rec({str(k): sorted([(str(dst), weight) for dst, weight in _items(v)], key=lambda x: x[0]) for k, v in sorted(G.items(), key=lambda x: str(x[0]))})
serialized = json.dumps(Rec({"G": sorted_G, "n": n, "colours": colours, "labels": labels}), sort_keys=True, default=str).encode()
png_filename = f"/tmp/graph_{hashlib.sha256(serialized).hexdigest()[:16]}.png"
try:
from graphviz import Digraph, Graph
except ImportError:
print("Please install graphviz: pip install graphviz")
return
if not G:
print("Empty graph")
return
print("\n")
all_nodes = set(G.keys())
edges = [(src, dst, weight) for src in G for dst, weight in _items(G[src])]
if not directed:
edges = [(src, dst, w) for src, dst, w in edges if str(src) <= str(dst) or src not in G.get(dst, Rec())]
all_nodes.update(dst for _, dst, _ in edges)
if n is not None:
all_nodes.update(range(n))
for spec in (colours, labels):
if isinstance(spec, (list, str)):
all_nodes.update(range(len(spec)))
dot = (Digraph if directed else Graph)(comment="The Graph")
dot.attr(rankdir="TB")
dot.attr(bgcolor="transparent")
dot.node_attr.update(style="filled", fillcolor="transparent", color="white", fontcolor="white")
dot.edge_attr.update(color="blue", fontcolor="white")
for node in sorted(all_nodes, key=str):
dot.node(str(node), **_node_attrs(_per_node(colours, node), _per_node(labels, node)))
for src, dst, weight in edges:
for one in (weight if isinstance(weight, list) else [weight]):
dot.edge(str(src), str(dst), **_edge_attrs(one, show_weights))
try:
print(dot.pipe(format="ascii", encoding="utf-8"))
except Exception:
try:
base_name = png_filename[:-4]
if not os.path.exists(png_filename):
dot.render(base_name, format="png", cleanup=True, view=False)
if os.system(f"timg {png_filename}") != 0:
raise RuntimeError("timg failed to run (is it installed?)")
except Exception as e:
print(f"Failed to render/display PNG: {e}")
print(f"\nDOT source:\n\n{dot.source}")