Skip to content

TUI

Terminal user interface (TUI) helper functions and components.

diff2rich(diff, *, console=Console())

Show rich representation of notebook diff in terminal.

Source code in databooks/tui.py
 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
def diff2rich(
    diff: DiffContents,
    *,
    console: Console = Console(),
) -> None:
    """Show rich representation of notebook diff in terminal."""
    a_nb, b_nb = (
        (
            JupyterNotebook.model_validate_json(c)
            if c is not None
            else JupyterNotebook(
                nbformat=0, nbformat_minor=0, metadata=NotebookMetadata(), cells=[]
            )
        )
        for c in (diff.a.contents, diff.b.contents)
    )
    cols = Columns(
        [
            Rule(
                f"{ab}/{c['path'].resolve().name if c['path'] is not None else 'null'}"
            )
            for ab, c in asdict(diff).items()
            if ab in ("a", "b")
        ],
        width=console.width // 2,
        padding=(0, 0),
    )
    console.print(cols, a_nb - b_nb)

diffs2rich(diffs, *, context=False, export_kwargs=None, **console_kwargs)

diffs2rich(
    diffs: List[DiffContents],
    *,
    context: ImgFmt,
    **kwargs: Any,
) -> str
diffs2rich(
    diffs: List[DiffContents],
    *,
    context: bool,
    **kwargs: Any,
) -> None

Show rich representation of notebook diff in terminal.

Parameters:

Name Type Description Default
diffs List[DiffContents]

databooks.git_utils.DiffContents for rendering

required
context Union[ImgFmt, bool]

specify context - ImgFmt to export outputs, True for pager

False
export_kwargs Optional[Dict[str, Any]]

keyword arguments for exporting prints (as a dictionary)

None
console_kwargs Any

keyword arguments to be passed to Console

{}

Returns:

Type Description
Optional[str]

console output if context is ImgFmt, else None

Source code in databooks/tui.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def diffs2rich(
    diffs: List[DiffContents],
    *,
    context: Union[ImgFmt, bool] = False,
    export_kwargs: Optional[Dict[str, Any]] = None,
    **console_kwargs: Any,
) -> Optional[str]:
    """
    Show rich representation of notebook diff in terminal.

    :param diffs: `databooks.git_utils.DiffContents` for rendering
    :param context: specify context - `ImgFmt` to export outputs, `True` for `pager`
    :param export_kwargs: keyword arguments for exporting prints (as a dictionary)
    :param console_kwargs: keyword arguments to be passed to `Console`
    :return: console output if `context` is `ImgFmt`, else `None`
    """
    theme = console_kwargs.pop("theme", DATABOOKS_TUI)
    if isinstance(context, ImgFmt):
        console_kwargs["file"] = StringIO()
    console = Console(record=isinstance(context, ImgFmt), theme=theme, **console_kwargs)
    ctx_map: Dict[Union[ImgFmt, bool], AbstractContextManager] = {
        True: console.pager(styles=True),
        False: nullcontext(),
    }
    with ctx_map.get(context, nullcontext()):
        for diff in diffs:
            diff2rich(diff, console=console)
    if isinstance(context, ImgFmt):
        return getattr(console, f"export_{context.name}")(**(export_kwargs or {}))

nb2rich(path, console=Console())

Show rich representation of notebook in terminal.

Source code in databooks/tui.py
23
24
25
26
27
28
29
def nb2rich(
    path: Path,
    console: Console = Console(),
) -> None:
    """Show rich representation of notebook in terminal."""
    notebook = JupyterNotebook.parse_file(path)
    console.print(Rule(path.resolve().name), notebook)

nbs2rich(paths, *, context=False, export_kwargs=None, **console_kwargs)

nbs2rich(
    paths: List[Path], *, context: ImgFmt, **kwargs: Any
) -> str
nbs2rich(
    paths: List[Path], *, context: bool, **kwargs: Any
) -> None

Show rich representation of notebooks in terminal.

Parameters:

Name Type Description Default
paths List[Path]

notebook paths to print

required
context Union[ImgFmt, bool]

specify context - ImgFmt to export outputs, True for pager

False
export_kwargs Optional[Dict[str, Any]]

keyword arguments for exporting prints (as a dictionary)

None
console_kwargs Any

keyword arguments to be passed to Console

{}

Returns:

Type Description
Optional[str]

console output if context is ImgFmt, else None

Source code in databooks/tui.py
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
def nbs2rich(
    paths: List[Path],
    *,
    context: Union[ImgFmt, bool] = False,
    export_kwargs: Optional[Dict[str, Any]] = None,
    **console_kwargs: Any,
) -> Optional[str]:
    """
    Show rich representation of notebooks in terminal.

    :param paths: notebook paths to print
    :param context: specify context - `ImgFmt` to export outputs, `True` for `pager`
    :param export_kwargs: keyword arguments for exporting prints (as a dictionary)
    :param console_kwargs: keyword arguments to be passed to `Console`
    :return: console output if `context` is `ImgFmt`, else `None`
    """
    if "record" in console_kwargs:
        raise ValueError(
            "Specify `record` parameter of console via `context` argument."
        )
    theme = console_kwargs.pop("theme", DATABOOKS_TUI)
    if isinstance(context, ImgFmt):
        console_kwargs["file"] = StringIO()
    console = Console(record=isinstance(context, ImgFmt), theme=theme, **console_kwargs)
    ctx_map: Dict[Union[ImgFmt, bool], AbstractContextManager] = {
        True: console.pager(styles=True),
        False: nullcontext(),
    }
    with ctx_map.get(context, nullcontext()):
        for path in paths:
            nb2rich(path, console=console)
    if isinstance(context, ImgFmt):
        return getattr(console, f"export_{context.name}")(**(export_kwargs or {}))