-
Notifications
You must be signed in to change notification settings - Fork 331
/
jupyter.ts
739 lines (666 loc) · 21.9 KB
/
jupyter.ts
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
/*
* jupyter.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import { basename, dirname, join, relative } from "../../deno_ral/path.ts";
import { satisfies } from "semver/mod.ts";
import { existsSync } from "fs/mod.ts";
import { error } from "../../deno_ral/log.ts";
import * as ld from "../../core/lodash.ts";
import { readYamlFromMarkdown } from "../../core/yaml.ts";
import { isInteractiveSession } from "../../core/platform.ts";
import { partitionMarkdown } from "../../core/pandoc/pandoc-partition.ts";
import { dirAndStem, normalizePath, removeIfExists } from "../../core/path.ts";
import { runningInCI } from "../../core/ci-info.ts";
import {
isJupyterNotebook,
jupyterAssets,
jupyterFromJSON,
jupyterKernelspecFromMarkdown,
jupyterToMarkdown,
kJupyterNotebookExtensions,
quartoMdToJupyter,
} from "../../core/jupyter/jupyter.ts";
import {
kBaseFormat,
kExecuteDaemon,
kExecuteEnabled,
kExecuteIpynb,
kFigDpi,
kFigFormat,
kFigPos,
kIncludeAfterBody,
kIncludeInHeader,
kIpynbFilters,
kIpynbProduceSourceNotebook,
kKeepHidden,
kKeepIpynb,
kNotebookPreserveCells,
kRemoveHidden,
} from "../../config/constants.ts";
import { Format } from "../../config/types.ts";
import {
isHtmlCompatible,
isHtmlDashboardOutput,
isIpynbOutput,
isLatexOutput,
isMarkdownOutput,
isPresentationOutput,
} from "../../config/format.ts";
import {
executeKernelKeepalive,
executeKernelOneshot,
JupyterExecuteOptions,
} from "./jupyter-kernel.ts";
import {
JupyterKernelspec,
JupyterNotebook,
JupyterWidgetDependencies,
} from "../../core/jupyter/types.ts";
import {
includesForJupyterWidgetDependencies,
} from "../../core/jupyter/widgets.ts";
import { RenderOptions, RenderResultFile } from "../../command/render/types.ts";
import {
DependenciesOptions,
ExecuteOptions,
ExecuteResult,
ExecutionEngine,
ExecutionTarget,
kJupyterEngine,
kQmdExtensions,
PandocIncludes,
PostProcessOptions,
RunOptions,
} from "../types.ts";
import { postProcessRestorePreservedHtml } from "../engine-shared.ts";
import { pythonExec } from "../../core/jupyter/exec.ts";
import {
jupyterNotebookFiltered,
markdownFromNotebookFile,
markdownFromNotebookJSON,
} from "../../core/jupyter/jupyter-filters.ts";
import { asMappedString } from "../../core/lib/mapped-text.ts";
import { MappedString, mappedStringFromFile } from "../../core/mapped-text.ts";
import { breakQuartoMd } from "../../core/lib/break-quarto-md.ts";
import { ProjectContext } from "../../project/types.ts";
import { isQmdFile } from "../qmd.ts";
import {
isJupyterPercentScript,
kJupyterPercentScriptExtensions,
markdownFromJupyterPercentScript,
} from "./percent.ts";
import {
inputFilesDir,
isServerShiny,
isServerShinyPython,
} from "../../core/render.ts";
import { jupyterCapabilities } from "../../core/jupyter/capabilities.ts";
import { runExternalPreviewServer } from "../../preview/preview-server.ts";
import { onCleanup } from "../../core/cleanup.ts";
import { projectOutputDir } from "../../project/project-shared.ts";
import { assert } from "testing/asserts.ts";
export const jupyterEngine: ExecutionEngine = {
name: kJupyterEngine,
defaultExt: ".qmd",
defaultYaml: (kernel?: string) => [
`jupyter: ${kernel || "python3"}`,
],
defaultContent: (kernel?: string) => {
kernel = kernel || "python3";
const lang = kernel.startsWith("python")
? "python"
: kernel.startsWith("julia")
? "julia"
: undefined;
if (lang) {
return [
"```{" + lang + "}",
"1 + 1",
"```",
];
} else {
return [];
}
},
validExtensions: () => [
...kJupyterNotebookExtensions,
...kJupyterPercentScriptExtensions,
...kQmdExtensions,
],
claimsFile: (file: string, ext: string) => {
return kJupyterNotebookExtensions.includes(ext.toLowerCase()) ||
isJupyterPercentScript(file);
},
claimsLanguage: (_language: string) => {
return false;
},
markdownForFile(file: string): Promise<MappedString> {
if (isJupyterNotebook(file)) {
const nbJSON = Deno.readTextFileSync(file);
const nb = JSON.parse(nbJSON) as JupyterNotebook;
return Promise.resolve(asMappedString(markdownFromNotebookJSON(nb)));
} else if (isJupyterPercentScript(file)) {
return Promise.resolve(
asMappedString(markdownFromJupyterPercentScript(file)),
);
} else {
return Promise.resolve(mappedStringFromFile(file));
}
},
target: async (
file: string,
_quiet?: boolean,
markdown?: MappedString,
project?: ProjectContext,
): Promise<ExecutionTarget | undefined> => {
assert(markdown);
// at some point we'll resolve a full notebook/kernelspec
let nb: JupyterNotebook | undefined;
if (isJupyterNotebook(file)) {
const nbJSON = Deno.readTextFileSync(file);
nb = JSON.parse(nbJSON) as JupyterNotebook;
}
// cache check for percent script
const isPercentScript = isJupyterPercentScript(file);
// get the metadata
const metadata = readYamlFromMarkdown(markdown.value);
// if this is a text markdown file then create a notebook for use as the execution target
if (isQmdFile(file) || isPercentScript) {
// write a transient notebook
const [fileDir, fileStem] = dirAndStem(file);
// See #4802
// I don't love using an extension other than .ipynb for this file,
// but doing something like .quarto.ipynb would require a lot
// of additional changes to our file handling code (without changes,
// our output files would be called $FILE.quarto.html, which
// is not what we want). So for now, we'll use .quarto_ipynb
const notebook = join(fileDir, fileStem + ".quarto_ipynb");
const target = {
source: file,
input: notebook,
markdown: markdown!,
metadata,
data: { transient: true, kernelspec: {} },
};
nb = await createNotebookforTarget(target, project);
target.data.kernelspec = nb.metadata.kernelspec;
return target;
} else if (isJupyterNotebook(file)) {
return {
source: file,
input: file,
markdown: markdown!,
metadata,
data: { transient: false, kernelspec: nb?.metadata.kernelspec },
};
} else {
return undefined;
}
},
partitionedMarkdown: async (file: string, format?: Format) => {
if (isJupyterNotebook(file)) {
return partitionMarkdown(await markdownFromNotebookFile(file, format));
} else if (isJupyterPercentScript(file)) {
return partitionMarkdown(markdownFromJupyterPercentScript(file));
} else {
return partitionMarkdown(Deno.readTextFileSync(file));
}
},
filterFormat: (
source: string,
options: RenderOptions,
format: Format,
) => {
// if this is shiny server and the user hasn't set keep-hidden then
// set it as well as the attibutes required to remove the hidden blocks
if (
isServerShinyPython(format, kJupyterEngine) &&
format.render[kKeepHidden] !== true
) {
format = ld.cloneDeep(format);
format.render[kKeepHidden] = true;
format.metadata[kRemoveHidden] = "all";
}
if (isJupyterNotebook(source)) {
// see if we want to override execute enabled
let executeEnabled: boolean | null | undefined;
// we never execute for a dev server reload
if (options.devServerReload) {
executeEnabled = false;
// if a specific ipynb execution policy is set then reflect it
} else if (typeof (format.execute[kExecuteIpynb]) === "boolean") {
executeEnabled = format.execute[kExecuteIpynb];
// if a specific execution policy is set then reflect it
} else if (typeof (format.execute[kExecuteEnabled]) == "boolean") {
executeEnabled = format.execute[kExecuteEnabled];
// otherwise default to NOT executing
} else {
executeEnabled = false;
}
// return format w/ execution policy
if (executeEnabled !== undefined) {
return {
...format,
execute: {
...format.execute,
[kExecuteEnabled]: executeEnabled,
},
};
// otherwise just return the original format
} else {
return format;
}
// not an ipynb
} else {
return format;
}
},
execute: async (options: ExecuteOptions): Promise<ExecuteResult> => {
// create the target input if we need to (could have been removed
// by the cleanup step of another render in this invocation)
if (
(isQmdFile(options.target.source) ||
isJupyterPercentScript(options.target.source)) &&
!existsSync(options.target.input)
) {
await createNotebookforTarget(options.target);
}
// determine the kernel (it's in the custom execute options data)
let kernelspec = (options.target.data as JupyterTargetData).kernelspec;
// determine execution behavior
const execute = options.format.execute[kExecuteEnabled] !== false;
if (execute) {
// if yaml front matter has a different kernel then use it
if (isJupyterNotebook(options.target.source)) {
kernelspec = await ensureYamlKernelspec(options.target, kernelspec) ||
kernelspec;
}
// jupyter back end requires full path to input (to ensure that
// keepalive kernels are never re-used across multiple inputs
// that happen to share a hash)
const execOptions = {
...options,
target: {
...options.target,
input: normalizePath(options.target.input),
},
};
// use daemon by default if we are in an interactive session (terminal
// or rstudio) and not running in a CI system.
let executeDaemon = options.format.execute[kExecuteDaemon];
if (executeDaemon === null || executeDaemon === undefined) {
if (await disableDaemonForNotebook(options.target)) {
executeDaemon = false;
} else {
executeDaemon = isInteractiveSession() && !runningInCI();
}
}
const jupyterExecOptions: JupyterExecuteOptions = {
kernelspec,
python_cmd: await pythonExec(kernelspec),
supervisor_pid: options.previewServer ? Deno.pid : undefined,
...execOptions,
};
if (executeDaemon === false || executeDaemon === 0) {
await executeKernelOneshot(jupyterExecOptions);
} else {
await executeKernelKeepalive(jupyterExecOptions);
}
}
// convert to markdown and write to target (only run notebook filters
// if the source is an ipynb file)
const nbContents = await jupyterNotebookFiltered(
options.target.input,
isJupyterNotebook(options.target.source)
? options.format.execute[kIpynbFilters]
: [],
);
const nb = jupyterFromJSON(nbContents);
// cells tagged 'shinylive' should be emmited as markdown
fixupShinyliveCodeCells(nb);
const assets = jupyterAssets(
options.target.input,
options.format.pandoc.to,
);
// Preserve the cell metadata if users have asked us to, or if this is dashboard
// that is coming from a non-qmd source
const preserveCellMetadata =
options.format.render[kNotebookPreserveCells] === true ||
(isHtmlDashboardOutput(options.format.identifier[kBaseFormat]) &&
!isQmdFile(options.target.source));
// NOTE: for perforance reasons the 'nb' is mutated in place
// by jupyterToMarkdown (we don't want to make a copy of a
// potentially very large notebook) so should not be relied
// on subseuqent to this call
const result = await jupyterToMarkdown(
nb,
{
executeOptions: options,
language: nb.metadata.kernelspec.language.toLowerCase(),
assets,
execute: options.format.execute,
keepHidden: options.format.render[kKeepHidden],
toHtml: isHtmlCompatible(options.format),
toLatex: isLatexOutput(options.format.pandoc),
toMarkdown: isMarkdownOutput(options.format),
toIpynb: isIpynbOutput(options.format.pandoc),
toPresentation: isPresentationOutput(options.format.pandoc),
figFormat: options.format.execute[kFigFormat],
figDpi: options.format.execute[kFigDpi],
figPos: options.format.render[kFigPos],
preserveCellMetadata,
preserveCodeCellYaml:
options.format.render[kIpynbProduceSourceNotebook] === true,
},
);
// return dependencies as either includes or raw dependencies
let includes: PandocIncludes | undefined;
let engineDependencies: Record<string, Array<unknown>> | undefined;
if (options.dependencies) {
includes = executeResultIncludes(options.tempDir, result.dependencies);
} else {
const dependencies = executeResultEngineDependencies(result.dependencies);
if (dependencies) {
engineDependencies = {
[kJupyterEngine]: dependencies,
};
}
}
// if it's a transient notebook then remove it
// (unless keep-ipynb was specified)
cleanupNotebook(options.target, options.format);
// Create markdown from the result
const outputs = result.cellOutputs.map((output) => output.markdown);
if (result.notebookOutputs) {
if (result.notebookOutputs.prefix) {
outputs.unshift(result.notebookOutputs.prefix);
}
if (result.notebookOutputs.suffix) {
outputs.push(result.notebookOutputs.suffix);
}
}
const markdown = outputs.join("");
// return results
return {
engine: kJupyterEngine,
markdown: markdown,
supporting: [join(assets.base_dir, assets.supporting_dir)],
filters: [],
pandoc: result.pandoc,
includes,
engineDependencies,
preserve: result.htmlPreserve,
postProcess: result.htmlPreserve &&
(Object.keys(result.htmlPreserve).length > 0),
};
},
executeTargetSkipped: cleanupNotebook,
dependencies: (options: DependenciesOptions) => {
const includes: PandocIncludes = {};
if (options.dependencies) {
const includeFiles = includesForJupyterWidgetDependencies(
options.dependencies as JupyterWidgetDependencies[],
options.tempDir,
);
if (includeFiles.inHeader) {
includes[kIncludeInHeader] = [includeFiles.inHeader];
}
if (includeFiles.afterBody) {
includes[kIncludeAfterBody] = [includeFiles.afterBody];
}
}
return Promise.resolve({
includes,
});
},
run: async (options: RunOptions): Promise<void> => {
// semver doesn't support 4th component
const asSemVer = (version: string) => {
const v = version.split(".");
if (v.length > 3) {
return `${v[0]}.${v[1]}.${v[2]}`;
} else {
return version;
}
};
// confirm required version of shiny
const kShinyVersion = ">=0.6";
let shinyError: string | undefined;
const caps = await jupyterCapabilities();
if (!caps?.shiny) {
shinyError =
"The shiny package is required for documents with server: shiny";
} else if (!satisfies(asSemVer(caps.shiny), asSemVer(kShinyVersion))) {
shinyError =
`The shiny package version must be ${kShinyVersion} for documents with server: shiny`;
}
if (shinyError) {
shinyError +=
"\n\nInstall the latest version of shiny with pip install --upgrade shiny\n";
error(shinyError);
throw new Error();
}
const [_dir] = dirAndStem(options.input);
const appFile = "app.py";
const cmd = [
...await pythonExec(),
"-m",
"shiny",
"run",
appFile,
"--host",
options.host!,
"--port",
String(options.port!),
];
if (options.reload) {
cmd.push("--reload");
cmd.push(`--reload-includes`);
cmd.push(`*.py`);
}
// start server
const readyPattern = /(http:\/\/(?:localhost|127\.0\.0\.1)\:\d+\/?[^\s]*)/;
const server = runExternalPreviewServer({
cmd,
readyPattern,
cwd: dirname(options.input),
});
await server.start();
// stop the server onCleanup
onCleanup(async () => {
await server.stop();
});
// notify when ready
if (options.onReady) {
options.onReady();
}
// run the server
return server.serve();
},
postRender: async (file: RenderResultFile, _context?: ProjectContext) => {
// discover non _files dir resources for server: shiny and amend app.py with them
if (isServerShiny(file.format)) {
const [dir] = dirAndStem(file.input);
const filesDir = join(dir, inputFilesDir(file.input));
const extraResources = file.resourceFiles
.filter((resource) => !resource.startsWith(filesDir))
.map((resource) => relative(dir, resource));
const appScriptDir = _context ? projectOutputDir(_context) : dir;
const appScript = join(appScriptDir, `app.py`);
if (existsSync(appScript)) {
// compute static assets
const staticAssets = [inputFilesDir(file.input), ...extraResources];
// check for (illegal) parent dir assets
const parentDirAssets = staticAssets.filter((asset) =>
asset.startsWith("..")
);
if (parentDirAssets.length > 0) {
error(
`References to files in parent directories found in document with server: shiny ` +
`(${basename(file.input)}): ${
JSON.stringify(parentDirAssets)
}. All resource files referenced ` +
`by Shiny documents must exist in the same directory as the source file.`,
);
throw new Error();
}
// In the app.py file, replace the placeholder with the list of static assets.
let appContents = Deno.readTextFileSync(appScript);
appContents = appContents.replace(
"##STATIC_ASSETS_PLACEHOLDER##",
JSON.stringify(staticAssets),
);
Deno.writeTextFileSync(appScript, appContents);
}
}
},
postprocess: (options: PostProcessOptions) => {
postProcessRestorePreservedHtml(options);
return Promise.resolve();
},
canFreeze: true,
generatesFigures: true,
ignoreDirs: () => {
return ["venv", "env"];
},
canKeepSource: (target: ExecutionTarget) => {
return !isJupyterNotebook(target.source);
},
intermediateFiles: (input: string) => {
const files: string[] = [];
const [fileDir, fileStem] = dirAndStem(input);
if (!isJupyterNotebook(input)) {
files.push(join(fileDir, fileStem + ".ipynb"));
} else if (
[...kQmdExtensions, ...kJupyterPercentScriptExtensions].some((ext) => {
return existsSync(join(fileDir, fileStem + ext));
})
) {
files.push(input);
}
return files;
},
};
async function ensureYamlKernelspec(
target: ExecutionTarget,
kernelspec: JupyterKernelspec,
) {
const markdown = target.markdown.value;
const yamlJupyter = readYamlFromMarkdown(markdown)?.jupyter;
if (yamlJupyter && typeof yamlJupyter !== "boolean") {
const [yamlKernelspec, _] = await jupyterKernelspecFromMarkdown(markdown);
if (yamlKernelspec.name !== kernelspec.name) {
const nb = jupyterFromJSON(Deno.readTextFileSync(target.source));
nb.metadata.kernelspec = yamlKernelspec;
Deno.writeTextFileSync(target.source, JSON.stringify(nb, null, 2));
return yamlKernelspec;
}
}
}
function fixupShinyliveCodeCells(nb: JupyterNotebook) {
if (nb.metadata.kernelspec.language === "python") {
nb.cells.forEach((cell) => {
if (
cell.cell_type === "code" && cell.metadata.tags?.includes("shinylive")
) {
cell.cell_type = "markdown";
cell.metadata = {};
cell.source = [
"```{shinylive-python}\n",
...cell.source,
"\n```",
];
delete cell.execution_count;
delete cell.outputs;
}
});
}
}
async function createNotebookforTarget(
target: ExecutionTarget,
project?: ProjectContext,
) {
const nb = await quartoMdToJupyter(target.markdown.value, true, project);
Deno.writeTextFileSync(target.input, JSON.stringify(nb, null, 2));
return nb;
}
// mitigate conflict between pexpect and our daamonization, see
// https://github.com/quarto-dev/quarto-cli/discussions/728
async function disableDaemonForNotebook(target: ExecutionTarget) {
const kShellMagics = [
"cd",
"cat",
"cp",
"env",
"ls",
"man",
"mkdir",
"more",
"mv",
"pwd",
"rm",
"rmdir",
];
const nb = await breakQuartoMd(target.markdown);
for (const cell of nb.cells) {
if (ld.isObject(cell.cell_type)) {
const language = (cell.cell_type as { language: string }).language;
if (language === "python") {
if (cell.source.value.startsWith("!")) {
return true;
}
return (kShellMagics.some((cmd) =>
cell.source.value.includes("%" + cmd + " ") ||
cell.source.value.includes("!" + cmd + " ") ||
cell.source.value.startsWith(cmd + " ")
));
}
}
}
return false;
}
function cleanupNotebook(target: ExecutionTarget, format: Format) {
// remove transient notebook if appropriate
const data = target.data as JupyterTargetData;
if (data.transient) {
if (!format.execute[kKeepIpynb]) {
removeIfExists(target.input);
}
}
}
interface JupyterTargetData {
transient: boolean;
kernelspec: JupyterKernelspec;
}
function executeResultIncludes(
tempDir: string,
widgetDependencies?: JupyterWidgetDependencies,
): PandocIncludes | undefined {
if (widgetDependencies) {
const includes: PandocIncludes = {};
const includeFiles = includesForJupyterWidgetDependencies(
[widgetDependencies],
tempDir,
);
if (includeFiles.inHeader) {
includes[kIncludeInHeader] = [includeFiles.inHeader];
}
if (includeFiles.afterBody) {
includes[kIncludeAfterBody] = [includeFiles.afterBody];
}
return includes;
} else {
return undefined;
}
}
function executeResultEngineDependencies(
widgetDependencies?: JupyterWidgetDependencies,
): Array<unknown> | undefined {
if (widgetDependencies) {
return [widgetDependencies];
} else {
return undefined;
}
}