-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path_repr.py
More file actions
207 lines (167 loc) · 6.14 KB
/
_repr.py
File metadata and controls
207 lines (167 loc) · 6.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
83
84
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# SPDX-License-Identifier: MPL-2.0
from __future__ import annotations
import json
import warnings
from textwrap import dedent, indent
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Literal, TypeAlias
if TYPE_CHECKING:
from collections.abc import Callable, Container, Iterable, Mapping
from . import SessionInfo, _TableHeader
MimeWidget = Literal["application/vnd.jupyter.widget-view+json"]
SupportedMime: TypeAlias = Literal[
"text/plain",
"text/markdown",
"text/html",
"application/json",
MimeWidget,
]
_ReprCB = Callable[[SessionInfo], str | dict[str, Any]]
MIME_WIDGET: MimeWidget = "application/vnd.jupyter.widget-view+json"
def repr_markdown(si: SessionInfo) -> str:
"""Generate Markdown representation."""
# no extra lines possible in markdown tables, so do multiple tables
return "\n\n".join(
part
for header, rows in si._table_parts().items() # noqa: SLF001
if (part := _fmt_markdown(header, rows))
)
def _fmt_markdown(header: _TableHeader, rows: Iterable[tuple[str, str]]) -> str:
rows = list(rows)
if not rows:
return ""
widths = [max(len(e) for e in col) for col in zip(*(header, *rows), strict=True)]
row_template = "| " + " | ".join(f"{{:<{w}}}" for w in widths) + " |"
sep = row_template.format(*(("-" * w) for w in widths))
rows_fmt = "\n".join(row_template.format(*row) for row in rows)
return f"{row_template.format(*header)}\n{sep}\n{rows_fmt}"
def repr_html(si: SessionInfo) -> str:
"""Generate static HTML representation."""
content, deps = repr_html_parts(si)
if deps:
deps = dedent(
f"""
<details>
<summary>Dependencies</summary>
{indent(deps, " " * 8)}
</details>
"""
).strip()
return dedent(
f"""
{content}
{deps if deps else ""}
<details>
<summary>Copyable Markdown</summary>
<pre>{repr_markdown(si)}</pre>
</details>
""",
).strip()
def repr_html_parts(si: SessionInfo) -> tuple[str, str | None]:
"""Generate parts for HTML representation."""
parts = {
header: part
for header, rows in si._table_parts().items() # noqa: SLF001
if (part := _fmt_html(header, rows))
}
shown_parts = [part for header, part in parts.items() if header[0] != "Dependency"]
nl = "\n" # Python 3.10 can’t do backslashes in f-strings
content = f"""
<table class=table>
{indent(nl.join(shown_parts), " " * 4)}
</table>
"""
if deps := parts.get(("Dependency", "Version")):
deps = _scrollable_table(deps)
return content, deps
def _scrollable_table(inner: str) -> str:
return dedent(
f"""
<div style="max-height: min(500px, 80vh); overflow-y: auto;">
<table class=table>
{indent(inner, " " * 8)}
</table>
</div>
""",
).strip()
COLORS = dict(
fg1="var(--jp-ui-font-color1, var(--vscode-editor-foreground, #212529))",
bg0="var(--jp-layout-color0, var(--vscode-editor-background, #f8f9fa))",
bg1="var(--jp-layout-color1, var(--vscode-editor-background, #f8f9fa))",
bg2="var(--jp-layout-color2, var(--vscode-tree-tableOddRowsBackground, #f1f3f4))",
)
def row_bg(i: int) -> str:
return COLORS["bg1" if i % 2 == 0 else "bg2"]
def _fmt_html(header: _TableHeader, rows: Iterable[tuple[str, str]]) -> str:
def strengthen(k: str) -> str:
return f"<strong>{k}</strong>" if header[0] == "Package" else k
rows_list = list(rows)
if not rows_list:
return ""
trs = "\n".join(
f' <tr style="background-color: {row_bg(i)}; color: {COLORS["fg1"]};">'
f"<td>{strengthen(k)}</td><td>{v}</td></tr>"
for i, (k, v) in enumerate(rows_list)
)
th = f" <tr><th>{header[0]}</th><th>{header[1]}</th></tr>"
thead_style = (
f'style="position: sticky; top: 0; background-color: {COLORS["bg0"]}; '
f'color: {COLORS["fg1"]};"'
)
thead = f"<thead {thead_style}>\n{th}\n</thead>"
return f"{thead}\n<tbody>\n{trs}\n</tbody>"
def repr_json(si: SessionInfo) -> str:
parts = si._table_parts() # noqa: SLF001
return json.dumps(
dict(
packages=_repr_json_part(parts["Package", "Version"]),
**(
dict(dependencies=_repr_json_part(parts["Dependency", "Version"]))
if ("Dependency", "Version") in parts
else {}
),
info=dict(parts["Component", "Info"]),
),
)
def _repr_json_part(rows: Iterable[tuple[str, str]]) -> list[dict[str, str]]:
return [dict(package=k, version=v) for k, v in rows]
def repr_widget(si: SessionInfo) -> dict[str, str]:
widget_bundle = si.widget()._repr_mimebundle_()
return widget_bundle[MIME_WIDGET] # type: ignore[no-any-return]
MIME_REPRS: Mapping[SupportedMime, _ReprCB] = MappingProxyType(
{
"text/plain": repr,
"text/markdown": repr_markdown,
"text/html": repr_html,
"application/json": repr_json,
MIME_WIDGET: repr_widget,
}
)
DEFAULT_EXCLUDE = {"application/json"}
def repr_mimebundle(
si: SessionInfo,
include: Container[str] | None = None,
exclude: Container[str] | None = None,
**_kwargs: object,
) -> dict[SupportedMime, Any]:
"""Generate MIME bundle representations.
:param include: MIME types to include.
:param exclude: MIME types to exclude.
"""
mb: dict[SupportedMime, Any] = {}
for mime, repr_fn in MIME_REPRS.items():
if include is not None and mime not in include:
continue
if exclude is not None and mime in exclude:
continue
if mime in DEFAULT_EXCLUDE and (include is None or mime not in include):
continue
try:
mb[mime] = repr_fn(si)
except ImportError as e:
msg = (
f"Failed to import dependencies for {mime} representation. "
f"({type(e).__name__}: {e})"
)
warnings.warn(msg, RuntimeWarning, stacklevel=8)
return mb