-
Notifications
You must be signed in to change notification settings - Fork 356
/
Copy pathnotebook.py
290 lines (251 loc) · 8.95 KB
/
notebook.py
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"""Notebook usage of LIT.
To use in LIT in colab or jupyter notebooks, create a LitWidget instance
with models and datasets to load. Optionally set the UI height and a proxy URL
if necessary. By default, the UI with render in the cell that creates the
instance. Set render=False to disable this, and manually render the UI in a cell
through the render() method. Use the stop() method to stop the server when done.
"""
from collections.abc import Mapping, Sequence
import html
import json
import os
import pathlib
import random
from typing import Any, Optional, cast
import urllib.parse
import attr
from IPython import display
from lit_nlp import dev_server
from lit_nlp import server_config
from lit_nlp.api import layout
from lit_nlp.lib import wsgi_serving
from tqdm import notebook
JsonDict = Mapping[str, Any]
try:
import google.colab # pylint: disable=g-import-not-at-top,unused-import
from google.colab import output # pylint: disable=g-import-not-at-top,unused-import # pytype: disable=import-error
is_colab = True
except (ImportError, ModuleNotFoundError):
is_colab = False
progress_indicator = notebook.tqdm
modules = layout.LitModuleName
LIT_NOTEBOOK_LAYOUT = layout.LitCanonicalLayout(
upper={
'Predictions': [
modules.SimpleDataTableModule,
*layout.MODEL_PREDS_MODULES,
],
'Explanations': [
modules.SimpleDatapointEditorModule,
*layout.MODEL_PREDS_MODULES,
modules.SalienceMapModule,
modules.LegacySequenceSalienceModule,
],
'Analysis': [
modules.MetricsModule,
modules.ConfusionMatrixModule,
modules.ScalarModule,
],
}
)
@attr.s(auto_attribs=True, kw_only=True)
class RenderConfig(object):
"""Config options for widget rendering."""
tab: Optional[str] = None
upper_tab: Optional[str] = None
layout: Optional[str] = None
dataset: Optional[str] = None
models: Optional[Sequence[str]] = None
datapoints: Optional[Sequence[JsonDict]] = None
def get_query_str(self):
"""Convert config object to query string for LIT URL."""
def _encode(v):
if isinstance(v, (list, tuple)):
return ','.join(v)
return v
string_params = {
k: _encode(v)
for k, v in attr.asdict(self).items()
if (v is not None and k != 'datapoints')
}
if self.datapoints:
for i, ex in enumerate(self.datapoints):
for field in ex:
string_params[f'data{i}_{field}'] = _encode(ex[field])
return '?' + urllib.parse.urlencode(string_params)
class LitWidget(object):
"""Class for using LIT inside notebooks."""
def __init__(
self,
*args,
height=1000,
render=False,
proxy_url=None,
layouts: Optional[layout.LitComponentLayouts] = None,
warm_start: bool = False,
**kw,
):
"""Start LIT server and optionally render the UI immediately.
Args:
*args: Positional arguments for the LitApp.
height: Height to display the LIT UI in pixels. Defaults to 1000.
render: Whether to render the UI when this object is constructed. Defaults
to False.
proxy_url: Optional proxy URL, if using in a notebook with a server proxy.
Defaults to None.
layouts: Optional custom UI layouts.
warm_start: If true, run predictions for every model on every compatible
dataset before returning a renderable widget.
**kw: Keyword arguments for the LitApp.
"""
app_flags = dict(server_config.get_flags())
app_flags['server_type'] = 'notebook'
app_flags['host'] = 'localhost'
app_flags['port'] = None
app_flags['warm_start'] = 1 if warm_start else 0
app_flags['warm_start_progress_indicator'] = progress_indicator
app_flags['sync_state'] = True
layouts = dict(layouts or {})
if 'notebook' not in layouts:
layouts['notebook'] = LIT_NOTEBOOK_LAYOUT
# This will be 'notebook' unless custom layouts are also given in Python.
app_flags['default_layout'] = list(layouts.keys())[0]
app_flags.update(kw)
lit_demo = dev_server.Server(*args, layouts=layouts, **app_flags)
self._server = cast(wsgi_serving.NotebookWsgiServer, lit_demo.serve())
self._height = height
self._proxy_url = proxy_url
if render:
self.render()
@property
def ui_state(self):
return self._server.app.ui_state_tracker.state
def stop(self):
"""Stop the LIT server."""
self._server.stop()
def render(
self,
height=None,
open_in_new_tab=False,
ui_params: Optional[RenderConfig] = None,
data: Optional[Sequence[JsonDict]] = None,
):
"""Render the LIT UI in the output cell.
To immediately analyze specifiic example(s), use the data= parameter:
widget.render(..., data=[{"prompt": "Hello world "}])
Args:
height: Optional height to display the LIT UI in pixels. If not specified,
then the height specified in the constructor is used.
open_in_new_tab: Whether to show the UI in a new tab instead of in the
output cell. Defaults to false.
ui_params: Optional configuration options for the LIT UI's state.
data: Optional examples to load directly to the UI (via URL params).
"""
if not height:
height = self._height
if not ui_params:
ui_params = RenderConfig()
if data:
ui_params.datapoints = data
if is_colab:
_display_colab(self._server.port, height, open_in_new_tab, ui_params)
else:
_display_jupyter(self._server.port, height, self._proxy_url,
open_in_new_tab, ui_params)
def _display_colab(port, height, open_in_new_tab, ui_params: RenderConfig):
"""Display the LIT UI in colab.
Args:
port: The port the LIT server is running on.
height: The height of the LIT UI in pixels.
open_in_new_tab: Whether to show the UI in a new tab instead of in the
output cell.
ui_params: RenderConfig of options for the LIT UI.
"""
params = ui_params.get_query_str()
path = f'/{params}'
if open_in_new_tab:
output.serve_kernel_port_as_window(port, path=path)
else:
output.serve_kernel_port_as_iframe(port, height=f'{height}', path=path)
def _display_jupyter(
port, height, proxy_url, open_in_new_tab, ui_params: RenderConfig
):
"""Display the LIT UI in jupyter.
Args:
port: The port the LIT server is running on.
height: The height of the LIT UI in pixels.
proxy_url: Optional proxy URL, if using in a notebook with a server proxy.
If not provided, LIT also checks to see if the environment variable
LIT_PROXY_URL is set, and if so, it uses that value as the proxy URL.
open_in_new_tab: Whether to show the UI in a new tab instead of in the
output cell.
ui_params: RenderConfig of options for the LIT UI.
"""
# Add height to jupyter output_scroll div to fully contain LIT UI.
output_scroll_height = height + 10
params = ui_params.get_query_str()
frame_id = 'lit-frame-{:08x}'.format(random.getrandbits(64))
if open_in_new_tab:
shell = """
<a href="javascript:void(0);" id="%HTML_ID%"></a>
<script>
(function() {
const urlStr = %URL% + '%PARAMS%'
const url = new URL(urlStr, window.location);
const port = %PORT%;
if (port) {
url.port = port;
}
const a = document.getElementById(%JSON_ID%);
a.innerHTML = url;
a.onclick = (e) => window.open(url, "_blank");
window.open(url, "_blank");
})();
</script>
"""
else:
shell = """
<style>div.output_scroll { height: %SCROLL_HEIGHT%px; }</style>
<iframe id='%HTML_ID%' width='100%' height='%HEIGHT%' frameborder='0'>
</iframe>
<script>
(function() {
const frame = document.getElementById(%JSON_ID%);
const urlStr = %URL% + '%PARAMS%'
const url = new URL(urlStr, window.location);
const port = %PORT%;
if (port) {
url.port = port;
}
frame.src = url;
})();
</script>
"""
if proxy_url is None:
proxy_url = os.environ.get('LIT_PROXY_URL')
if proxy_url is not None:
# Allow %PORT% in proxy_url.
proxy_url = proxy_url.replace('%PORT%', '%d' % port)
replacements = [
('%HTML_ID%', html.escape(frame_id, quote=True)),
('%JSON_ID%', json.dumps(frame_id)),
('%HEIGHT%', '%d' % height),
('%SCROLL_HEIGHT%', '%d' % output_scroll_height),
('%PORT%', '0'),
('%URL%', json.dumps(proxy_url)),
('%PARAMS%', '%s' % params),
]
else:
replacements = [
('%HTML_ID%', html.escape(frame_id, quote=True)),
('%JSON_ID%', json.dumps(frame_id)),
('%HEIGHT%', '%d' % height),
('%SCROLL_HEIGHT%', '%d' % output_scroll_height),
('%PORT%', '%d' % port),
('%URL%', json.dumps('/')),
('%PARAMS%', '%s' % params),
]
for (k, v) in replacements:
shell = shell.replace(k, v)
iframe = display.HTML(shell)
display.display(iframe)