from pathlib import Path from typing import Optional, Sequence import rich import rich.syntax import rich.tree from omegaconf import DictConfig, OmegaConf def print_config_tree( cfg: DictConfig, print_order: Sequence[str] = [], resolve: bool = False, log_dir: Optional[str] = None, ) -> None: """Prints the contents of a DictConfig as a tree structure using the Rich library. :param cfg: A DictConfig composed by Hydra. :param print_order: Determines in what order config components are printed. Default is ``("data", "model", "callbacks", "logger", "trainer", "paths", "extras")``. :param resolve: Whether to resolve reference fields of DictConfig. Default is ``False``. :param save_to_file: Whether to export config to the hydra output folder. Default is ``False``. """ style = "dim" tree = rich.tree.Tree("CONFIG", style=style, guide_style=style) queue = [] # add fields from `print_order` to queue for field in print_order: ( queue.append(field) if field in cfg else print( f"Field '{field}' not found in config. Skipping '{field}' config printing..." ) ) # add all the other fields to queue (not specified in `print_order`) for field in cfg: if field not in queue: queue.append(field) # generate config tree from queue for field in queue: branch = tree.add(field, style=style, guide_style=style) config_group = cfg[field] if isinstance(config_group, DictConfig): branch_content = OmegaConf.to_yaml(config_group, resolve=resolve) else: branch_content = str(config_group) branch.add(rich.syntax.Syntax(branch_content, "yaml")) # print config tree rich.print(tree) # save config tree to file if log_dir is not None: with open(Path(log_dir, "config_tree.log"), "w") as file: rich.print(tree, file=file)