-
Notifications
You must be signed in to change notification settings - Fork 347
/
Copy pathjupyter.ts
2041 lines (1858 loc) · 56.8 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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* jupyter.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
// deno-lint-ignore-file camelcase
import { ensureDirSync } from "fs/ensure_dir.ts";
import { dirname, extname, join, relative } from "../../deno_ral/path.ts";
import { walkSync } from "fs/walk.ts";
import * as colors from "fmt/colors.ts";
import { decodeBase64 as base64decode } from "encoding/base64.ts";
import { DumpOptions as StringifyOptions, stringify } from "yaml/mod.ts";
import { partitionCellOptions } from "../lib/partition-cell-options.ts";
import * as ld from "../lodash.ts";
import { shortUuid } from "../uuid.ts";
import {
extensionForMimeImageType,
kApplicationJavascript,
kApplicationRtf,
kImagePng,
kImageSvg,
kRestructuredText,
kTextHtml,
kTextLatex,
kTextPlain,
} from "../mime.ts";
import PngImage from "../png.ts";
import {
echoFenced,
hideCell,
hideCode,
hideOutput,
hideWarnings,
includeCell,
includeCode,
includeOutput,
includeWarnings,
} from "./tags.ts";
import {
cellLabel,
cellLabelValidator,
resolveCaptions,
shouldLabelCellContainer,
shouldLabelOutputContainer,
} from "./labels.ts";
import {
displayDataIsHtml,
displayDataIsImage,
displayDataIsJavascript,
displayDataIsJson,
displayDataIsLatex,
displayDataIsMarkdown,
displayDataIsTextPlain,
displayDataMimeType,
displayDataWithMarkdownMath,
isCaptionableData,
isDisplayData,
} from "./display-data.ts";
import { extractJupyterWidgetDependencies } from "./widgets.ts";
import { removeAndPreserveHtml } from "./preserve.ts";
import { pandocAsciify, pandocAutoIdentifier } from "../pandoc/pandoc-id.ts";
import { Metadata } from "../../config/types.ts";
import {
kCapLoc,
kCellAutoscroll,
kCellClasses,
kCellColab,
kCellColabType,
kCellColbOutputId,
kCellCollapsed,
kCellColumn,
kCellDeletable,
kCellFigAlign,
kCellFigAlt,
kCellFigCap,
kCellFigColumn,
kCellFigEnv,
kCellFigLink,
kCellFigPos,
kCellFigScap,
kCellFigSubCap,
kCellFormat,
kCellId,
kCellLabel,
kCellLanguage,
kCellLinesToNext,
kCellLstCap,
kCellLstLabel,
kCellMdIndent,
kCellName,
kCellOutHeight,
kCellOutWidth,
kCellPanel,
kCellRawMimeType,
kCellSlideshow,
kCellSlideshowSlideType,
kCellTblColumn,
kCodeFold,
kCodeLineNumbers,
kCodeOverflow,
kCodeSummary,
kEcho,
kError,
kEval,
kFigCapLoc,
kHtmlTableProcessing,
kInclude,
kLayout,
kLayoutAlign,
kLayoutNcol,
kLayoutNrow,
kLayoutVAlign,
kOutput,
kTblCap,
kTblCapLoc,
kTblColwidths,
kWarning,
} from "../../config/constants.ts";
import {
isJupyterKernelspec,
jupyterDefaultPythonKernelspec,
jupyterKernelspec,
jupyterKernelspecForLanguage,
jupyterKernelspecs,
} from "./kernels.ts";
import {
JupyterCell,
JupyterCellOutput,
JupyterCellWithOptions,
JupyterKernelspec,
JupyterNotebook,
JupyterOutput,
JupyterOutputDisplayData,
JupyterOutputFigureOptions,
JupyterOutputStream,
JupyterToMarkdownOptions,
JupyterToMarkdownResult,
} from "./types.ts";
import { figuresDir, inputFilesDir } from "../render.ts";
import { lines, trimEmptyLines } from "../lib/text.ts";
import { partitionYamlFrontMatter, readYamlFromMarkdown } from "../yaml.ts";
import { languagesInMarkdown } from "../../execute/engine-shared.ts";
import {
normalizePath,
pathWithForwardSlashes,
removeIfEmptyDir,
} from "../path.ts";
import { convertToHtmlSpans, hasAnsiEscapeCodes } from "../ansi-colors.ts";
import { kProjectType, ProjectContext } from "../../project/types.ts";
import { mergeConfigs } from "../config.ts";
import { encodeBase64 } from "encoding/base64.ts";
import {
isHtmlOutput,
isIpynbOutput,
isJatsOutput,
} from "../../config/format.ts";
import {
bookFixups,
fixupJupyterNotebook,
minimalFixups,
} from "./jupyter-fixups.ts";
import {
resolveUserExpressions,
userExpressionsFromCell,
} from "./jupyter-inline.ts";
import {
jupyterCellSrcAsLines,
jupyterCellSrcAsStr,
} from "./jupyter-shared.ts";
export const kQuartoMimeType = "quarto_mimetype";
export const kQuartoOutputOrder = "quarto_order";
export const kQuartoOutputDisplay = "quarto_display";
export const kJupyterNotebookExtensions = [
".ipynb",
];
export function isJupyterNotebook(file: string) {
return kJupyterNotebookExtensions.includes(extname(file).toLowerCase());
}
// option keys we handle internally so should not forward into generated markdown
export const kJupyterCellInternalOptionKeys = [
kEval,
kEcho,
kWarning,
kError,
kOutput,
kInclude,
kCellLabel,
kCellClasses,
kCellPanel,
kCellColumn,
kCellFigCap,
kCellFigSubCap,
kCellFigScap,
kFigCapLoc,
kTblCapLoc,
kCapLoc,
kCellFigColumn,
kCellTblColumn,
kCellFigLink,
kCellFigAlign,
kCellFigAlt,
kCellFigEnv,
kCellFigPos,
kCellLstLabel,
kCellLstCap,
kCellOutWidth,
kCellOutHeight,
kCellMdIndent,
kCodeFold,
kCodeLineNumbers,
kCodeSummary,
kCodeOverflow,
kHtmlTableProcessing,
];
export const kJupyterCellOptionKeys = kJupyterCellInternalOptionKeys.concat([
kLayoutAlign,
kLayoutVAlign,
kLayoutNcol,
kLayoutNrow,
kLayout,
kTblCap,
kTblColwidths,
]);
export const kJupyterCellStandardMetadataKeys = [
kCellCollapsed,
kCellAutoscroll,
kCellDeletable,
kCellFormat,
kCellName,
];
export const kJupyterCellThirdPartyMetadataKeys = [
// colab
kCellId,
kCellColab,
kCellColabType,
kCellColbOutputId,
// jupytext
kCellLinesToNext,
// nbdev
kCellLanguage,
];
export interface JupyterOutputExecuteResult extends JupyterOutputDisplayData {
execution_count: number;
}
export interface JupyterOutputError extends JupyterOutput {
ename: string;
evalue: string;
traceback: string[];
}
const countTicks = (code: string[]) => {
// FIXME do we need trim() here?
const countLeadingTicks = (s: string) => {
// count leading ticks using regexps
const m = s.match(/^\s*`+/);
if (m) {
return m[0].length;
} else {
return 0;
}
};
return Math.max(0, ...code.map((s) => countLeadingTicks(s)));
};
const ticksForCode = (code: string[]) => {
const n = Math.max(3, countTicks(code) + 1);
return "`".repeat(n);
};
export async function quartoMdToJupyter(
markdown: string,
includeIds: boolean,
project?: ProjectContext,
): Promise<JupyterNotebook> {
const [kernelspec, metadata] = await jupyterKernelspecFromMarkdown(
markdown,
project,
);
// notebook to return
const nb: JupyterNotebook = {
cells: [],
metadata: {
kernelspec,
...metadata,
},
nbformat: 4,
nbformat_minor: includeIds ? 5 : 4,
};
// regexes
const yamlRegEx = /^---\s*$/;
/^\s*```+\s*\{([a-zA-Z0-9_]+)( *[ ,].*)?\}\s*$/;
const startCodeCellRegEx = new RegExp(
"^(\\s*)(```+)\\s*\\{" + kernelspec.language.toLowerCase() +
"( *[ ,].*)?\\}\\s*$",
);
const startCodeRegEx = /^(\s*)```/;
const endCodeRegEx = (indent = "", backtickCount = 0) => {
return new RegExp("^" + indent + "`".repeat(backtickCount) + "\\s*$");
};
// read the file into lines
const inputContent = markdown;
// line buffer & code indent
let codeIndent = "";
const lineBuffer: string[] = [];
const flushLineBuffer = (
cell_type: "markdown" | "code" | "raw",
frontMatter?: boolean,
) => {
if (lineBuffer.length) {
if (lineBuffer[0] === "") {
lineBuffer.splice(0, 1);
}
if (lineBuffer[lineBuffer.length - 1] === "") {
lineBuffer.splice(lineBuffer.length - 1, 1);
}
// only use codeIndent for code cells
if (cell_type !== "code") {
codeIndent = "";
}
const cell: JupyterCell = {
cell_type,
metadata: codeIndent.length > 0 ? { [kCellMdIndent]: codeIndent } : {},
source: lineBuffer.map((line, index) => {
if (codeIndent.length > 0) {
line = line.replace(codeIndent, "");
}
return line + (index < (lineBuffer.length - 1) ? "\n" : "");
}),
};
if (includeIds) {
cell.id = shortUuid();
}
if (cell_type === "raw" && frontMatter) {
// delete 'jupyter' metadata since we've already transferred it
const yaml = readYamlFromMarkdown(jupyterCellSrcAsStr(cell));
if (yaml.jupyter) {
delete yaml.jupyter;
// write the cell only if there is metadata to write
if (Object.keys(yaml).length > 0) {
const yamlFrontMatter = trimEmptyLines(lines(stringify(yaml, {
indent: 2,
lineWidth: -1,
sortKeys: false,
skipInvalid: true,
})));
cell.source = [
"---\n",
...(yamlFrontMatter.map((line) => line + "\n")),
"---",
];
} else {
cell.source = [];
}
}
} else if (cell_type === "code") {
// see if there is embedded metadata we should forward into the cell metadata
const cellSrcLines = typeof cell.source === "string"
? lines(cell.source)
: cell.source;
const { yaml, source } = partitionCellOptions(
kernelspec.language.toLowerCase(),
cellSrcLines,
);
if (yaml && !Array.isArray(yaml) && typeof yaml === "object") {
// use label as id if necessary
if (includeIds && yaml[kCellLabel] && !yaml[kCellId]) {
yaml[kCellId] = jupyterAutoIdentifier(String(yaml[kCellLabel]));
}
const yamlKeys = Object.keys(yaml);
yamlKeys.forEach((key) => {
if (key === kCellId) {
if (includeIds) {
cell.id = String(yaml[key]);
}
delete yaml[key];
} else {
if (!kJupyterCellOptionKeys.includes(key)) {
cell.metadata[key] = yaml[key];
delete yaml[key];
}
}
});
// if we hit at least one we need to re-write the source
if (Object.keys(yaml).length < yamlKeys.length) {
const yamlOutput = jupyterCellOptionsAsComment(
kernelspec.language.toLowerCase(),
yaml,
);
cell.source = yamlOutput.concat(source);
}
}
// reset outputs and execution_count
cell.execution_count = null;
cell.outputs = [];
}
// if the source is empty then don't add it
const cellSrcLines = typeof cell.source === "string"
? lines(cell.source)
: cell.source;
cell.source = trimEmptyLines(cellSrcLines);
if (cell.source.length > 0) {
nb.cells.push(cell);
}
lineBuffer.splice(0, lineBuffer.length);
}
};
// loop through lines and create cells based on state transitions
let parsedFrontMatter = false,
inYaml = false,
inCodeCell = false,
inCode = false,
backtickCount = 0;
let currentLine = 0;
const contentLines = lines(inputContent);
for (currentLine = 0; currentLine < contentLines.length; ++currentLine) {
const line = contentLines[currentLine];
// yaml front matter
if (
yamlRegEx.test(line) && !inCodeCell && !inCode &&
contentLines[currentLine + 1]?.trim() !== "" // https://github.com/quarto-dev/quarto-cli/issues/8998
) {
if (inYaml) {
lineBuffer.push(line);
flushLineBuffer("raw", !parsedFrontMatter);
parsedFrontMatter = true;
inYaml = false;
} else {
flushLineBuffer("markdown");
lineBuffer.push(line);
inYaml = true;
}
} // begin code cell: ^```python
else if (!inCodeCell && startCodeCellRegEx.test(line)) {
flushLineBuffer("markdown");
inCodeCell = true;
codeIndent = line.match(startCodeCellRegEx)![1];
backtickCount = line.match(startCodeCellRegEx)![2].length;
// end code block: ^``` (tolerate trailing ws)
} else if (
inCodeCell && endCodeRegEx(codeIndent, backtickCount).test(line)
) {
// in a code cell, flush it
if (inCodeCell) {
inCodeCell = false;
flushLineBuffer("code");
codeIndent = "";
// otherwise this flips the state of in-code
} else {
inCode = !inCode;
codeIndent = "";
lineBuffer.push(line);
}
// begin code block: ^```
} else if (!inCodeCell && startCodeRegEx.test(line)) {
codeIndent = line.match(startCodeRegEx)![1];
inCode = true;
lineBuffer.push(line);
} else {
lineBuffer.push(line);
}
}
// if there is still a line buffer then make it a markdown cell
flushLineBuffer("markdown");
return nb;
}
export async function jupyterKernelspecFromMarkdown(
markdown: string,
project?: ProjectContext,
): Promise<[JupyterKernelspec, Metadata]> {
const config = project?.config;
const yaml = config
? mergeConfigs(config, readYamlFromMarkdown(markdown))
: readYamlFromMarkdown(markdown);
const yamlJupyter = yaml.jupyter;
// if there is no yaml.jupyter then detect the file's language(s) and
// find a kernelspec that supports this language
if (!yamlJupyter) {
const languages = languagesInMarkdown(markdown);
languages.add("python"); // python as a default/failsafe
for (const language of languages) {
const kernelspec = await jupyterKernelspecForLanguage(language);
if (kernelspec) {
return [kernelspec, {}];
}
}
const kernelspecs = await jupyterKernelspecs();
return Promise.reject(
new Error(
`No kernel found for any language checked (${
Array.from(languages).join(", ")
}) in any of the kernelspecs checked (${
Array.from(kernelspecs.values()).map((k) => k.name).join(", ")
}).`,
),
);
} else if (typeof yamlJupyter === "string") {
const kernel = yamlJupyter;
const kernelspec = await jupyterKernelspec(kernel);
if (kernelspec) {
return [kernelspec, {}];
} else {
return Promise.reject(
new Error(
`Jupyter kernel '${kernel}' not found. Known kernels: ${
Array.from((await jupyterKernelspecs()).values())
.map((kernel: JupyterKernelspec) => kernel.name).join(", ")
}. Run 'quarto check jupyter' with your python environment activated to check python version used.`,
),
);
}
} else if (typeof yamlJupyter === "object") {
const jupyter = { ...yamlJupyter } as Record<string, unknown>;
if (isJupyterKernelspec(jupyter.kernelspec)) {
const kernelspec = jupyter.kernelspec;
delete jupyter.kernelspec;
return [kernelspec, jupyter];
} else if (typeof (jupyter.kernel) === "string") {
const kernelspec = await jupyterKernelspec(jupyter.kernel);
if (kernelspec) {
delete jupyter.kernel;
return [kernelspec, jupyter];
} else {
return Promise.reject(
new Error(
`Jupyter kernel '${jupyter.kernel}' not found. Known kernels: ${
Array.from((await jupyterKernelspecs()).values())
.map((kernel: JupyterKernelspec) => kernel.name).join(", ")
}. Run 'quarto check jupyter' with your python environment activated to check python version used.`,
),
);
}
} else {
return Promise.reject(
new Error(
"Invalid Jupyter kernelspec (must include name, language, & display_name)",
),
);
}
} else {
return Promise.reject(
new Error(
"Invalid jupyter YAML metadata found in file (must be string or object)",
),
);
}
}
export function jupyterKernelspecFromFile(
file: string,
): Promise<[JupyterKernelspec, Metadata]> {
const markdown = Deno.readTextFileSync(file);
return jupyterKernelspecFromMarkdown(markdown);
}
export function jupyterFromFile(input: string): JupyterNotebook {
const nbContents = Deno.readTextFileSync(input);
return jupyterFromJSON(nbContents);
}
export function jupyterFromJSON(nbContents: string): JupyterNotebook {
// parse the notebook
const nbJSON = JSON.parse(nbContents);
const nb = nbJSON as JupyterNotebook;
// vscode doesn't write a language to the kernelspec so also try language_info
// google colab doesn't write a language at all, in that case try to deduce off of name
if (!nb.metadata.kernelspec?.language) {
if (nb.metadata.kernelspec) {
nb.metadata.kernelspec.language = nbJSON.metadata.language_info?.name;
if (
!nb.metadata.kernelspec.language &&
nb.metadata.kernelspec.name?.includes("python")
) {
nb.metadata.kernelspec.language = "python";
}
} else {
// provide default
nb.metadata.kernelspec = jupyterDefaultPythonKernelspec();
}
}
// validate that we have a language
if (!nb.metadata.kernelspec.language) {
throw new Error("No language set for Jupyter notebook");
}
// validate that we have cells
if (!nb.cells) {
throw new Error("No cells available in Jupyter notebook");
}
return nb;
}
export function jupyterAutoIdentifier(label: string) {
label = pandocAsciify(label);
label = label
// Replace all spaces with hyphens
.replace(/\s/g, "-")
// Remove invalid chars
.replace(/[^a-zA-Z0-9-_]/g, "")
// Remove everything up to the first letter
.replace(/^[^A-Za-z]+/, "");
// if it's empty then create a random id
if (label.length > 0) {
return label.slice(0, 64);
} else {
return shortUuid();
}
}
export interface JupyterNotebookAssetPaths {
base_dir: string;
files_dir: string;
figures_dir: string;
supporting_dir: string;
}
export function jupyterAssets(
input: string,
to?: string,
): JupyterNotebookAssetPaths {
// calculate and create directories
input = normalizePath(input);
const files_dir = join(dirname(input), inputFilesDir(input));
const figures_dir = join(files_dir, figuresDir(to));
ensureDirSync(figures_dir);
// determine supporting_dir (if there are no other figures dirs then it's
// the files dir, otherwise it's just the figures dir). note that
// supporting_dir is the directory that gets removed after a self-contained
// or non-keeping render is complete
let supporting_dir = files_dir;
for (
const walk of walkSync(join(files_dir), { maxDepth: 1 })
) {
if (walk.path !== files_dir && walk.path !== figures_dir) {
supporting_dir = figures_dir;
break;
}
}
const base_dir = dirname(input);
return {
base_dir,
files_dir: pathWithForwardSlashes(relative(base_dir, files_dir)),
figures_dir: pathWithForwardSlashes(relative(base_dir, figures_dir)),
supporting_dir: pathWithForwardSlashes(relative(base_dir, supporting_dir)),
};
}
export function cleanEmptyJupyterAssets(assets: JupyterNotebookAssetPaths) {
const figuresRemoved = removeIfEmptyDir(
join(assets.base_dir, assets.figures_dir),
);
const filesRemoved = removeIfEmptyDir(
join(assets.base_dir, assets.files_dir),
);
return figuresRemoved && filesRemoved;
}
// Attach fully rendered notebook to render services
// Render notebook only once per document
// Return cells with markdown instead of complete markdown
// filter output markdown cells rather than notebook input
export async function jupyterToMarkdown(
nb: JupyterNotebook,
options: JupyterToMarkdownOptions,
): Promise<JupyterToMarkdownResult> {
// perform fixups
const project = options.executeOptions.project;
const projType = project?.config?.project?.[kProjectType];
if (projType === "book") {
nb = fixupJupyterNotebook(nb, bookFixups);
} else if (project?.isSingleFile) {
nb = fixupJupyterNotebook(nb, options.fixups || "default");
} else if (
(project?.config?.title !== undefined &&
(projType === "default" || projType === undefined))
) {
nb = fixupJupyterNotebook(nb, minimalFixups);
} else {
nb = fixupJupyterNotebook(nb, options.fixups || "default");
}
// optional content injection / html preservation for html output
// that isn't an ipynb
const isHtml = options.toHtml && !options.toIpynb;
const dependencies = isHtml
? extractJupyterWidgetDependencies(nb)
: undefined;
const htmlPreserve = isHtml ? removeAndPreserveHtml(nb) : undefined;
// generate markdown
const cellOutputs: JupyterCellOutput[] = [];
// validate unique cell labels as we go
const validateCellLabel = cellLabelValidator();
// track current code cell index (for progress)
let codeCellIndex = 0;
let frontMatter = undefined;
for (let i = 0; i < nb.cells.length; i++) {
// Collection the markdown for this cell
const md: string[] = [];
// convert cell yaml to cell metadata
const cell = jupyterCellWithOptions(
i,
nb.metadata.kernelspec.language.toLowerCase(),
nb.cells[i],
);
// validate unique cell labels
validateCellLabel(cell);
// interpret cell slide_type for presentation output
const slideType = options.toPresentation
? cell.metadata[kCellSlideshow]?.[kCellSlideshowSlideType]
: undefined;
if (slideType) {
// write any implied delimeter (or skip entirely)
if (slideType === "skip") {
continue;
} else if (slideType == "slide" || slideType === "subslide") {
md.push("\n---\n\n");
} else if (slideType == "fragment") {
md.push("\n. . .\n\n");
} else if (slideType == "notes") {
md.push("\n:::::::::: notes\n\n");
}
}
// find the first yaml metadata block and hold it out
// note if it has a title
// at the end, if it doesn't have a title, then snip the title out
// markdown from cell
switch (cell.cell_type) {
case "markdown":
{
const markdownOptions = {
...options,
};
// If this is the front matter cell, don't wrap it in
// a cell envelope, as it need to be remain discoverable
if (frontMatter === undefined) {
frontMatter = partitionYamlFrontMatter(
jupyterCellSrcAsStr(cell),
)?.yaml;
if (frontMatter) {
markdownOptions.preserveCellMetadata = false;
}
}
md.push(...mdFromContentCell(cell, markdownOptions));
}
break;
case "raw":
md.push(...mdFromRawCell(cell, options));
break;
case "code":
md.push(...(await mdFromCodeCell(cell, ++codeCellIndex, options)));
break;
default:
throw new Error("Unexpected cell type " + cell.cell_type);
}
// terminate slide notes
if (slideType === "notes") {
md.push("\n::::::::::\n");
}
// newline
md.push("\n");
cellOutputs.push({
id: cell.id,
markdown: md.join(""),
metadata: cell.metadata,
options: cell.options,
});
}
// include jupyter metadata if we are targeting ipynb
let notebookOutputs = undefined;
if (options.toIpynb) {
const md: string[] = [];
md.push("---\n");
// If widgets are present, base64 encode their metadata to prevent true round
// tripping through YAML, which heavily mutates the metadata
const widgets = nb.metadata.widgets
? encodeBase64(JSON.stringify(nb.metadata.widgets))
: undefined;
const jupyterMetadata = {
jupyter: {
...nb.metadata,
widgets,
},
};
const yamlText = stringify(jupyterMetadata, {
indent: 2,
lineWidth: -1,
sortKeys: false,
skipInvalid: true,
});
md.push(yamlText);
md.push("---\n");
notebookOutputs = {
suffix: md.join(""),
};
}
// return markdown and any widget requirements
return {
cellOutputs,
notebookOutputs,
dependencies,
htmlPreserve,
};
}
export function jupyterCellWithOptions(
index: number,
language: string,
cell: JupyterCell,
): JupyterCellWithOptions {
const { yaml, optionsSource, source } = partitionCellOptions(
language,
jupyterCellSrcAsLines(cell),
);
// read any options defined in cell metadata
const metadataOptions: Record<string, unknown> = kJupyterCellOptionKeys
.reduce((options, key) => {
if (cell.metadata[key] !== undefined) {
options[key] = cell.metadata[key];
}
return options;
}, {} as Record<string, unknown>);
// combine metadata options with yaml options (giving yaml options priority)
const explicitOptions = {
...metadataOptions,
...yaml,
};
// if we have layout or tbl-colwidths and it's not a string then json encode it
[kLayout, kTblColwidths].forEach((option) => {
if (
explicitOptions[option] && typeof (explicitOptions[option]) !== "string"
) {
explicitOptions[option] = JSON.stringify(explicitOptions[option]);
}
});
// Resolve any tags that map to options
const tags = cell.metadata.tags;
const tagOptions = tagsToOptions(tags || []);
const options = {
...tagOptions,
...explicitOptions,
};
// Ensure that the cell has an id - the id will be
// unique within this notebook thanks to the index
const cellId = (cell: JupyterCell) => {
if (
options && options[kCellLabel] &&
typeof (options[kCellLabel]) === "string"
) {
return `cell-${options[kCellLabel]}`;
} else if (cell.id) {
return cell.id;
} else {
return `cell-${index}`;
}
};
return {
...cell,
id: cellId(cell),
source,
optionsSource,
options,
};
}
export function jupyterCellOptionsAsComment(
language: string,
options: Record<string, unknown>,
stringifyOptions?: StringifyOptions,
) {
if (Object.keys(options).length > 0) {
const cellYaml = stringify(options, {
indent: 2,
lineWidth: -1,
sortKeys: false,
skipInvalid: true,
...stringifyOptions,
});
const commentChars = langCommentChars(language);
const yamlOutput = trimEmptyLines(lines(cellYaml)).map((line) => {
line = optionCommentPrefix(commentChars[0]) + line +
optionCommentSuffix(commentChars[1]);
return line + "\n";
});
return yamlOutput;
} else {
return [];
}
}
export function mdFromContentCell(
cell: JupyterCellWithOptions,
options?: JupyterToMarkdownOptions,
) {
const contentCellEnvelope = createCellEnvelope(["cell", "markdown"], options);
// clone source for manipulation
const source = ld.cloneDeep(cell.source) as string[];
// handle user expressions (if any)
if (options && source) {
const userExpressions = userExpressionsFromCell(cell);
resolveUserExpressions(source, userExpressions, options);
}
// if we have attachments then extract them and markup the source
if (options && cell.attachments && source) {
// close source so we can modify it
Object.keys(cell.attachments).forEach((file, index) => {
const attachment = cell.attachments![file];
for (const mimeType of Object.keys(attachment)) {
if (extensionForMimeImageType(mimeType, undefined)) {
// save attachment in the figures dir
const imageFile = options.assets.figures_dir +
`/${cell.id}-${index + 1}-${file}`;
const outputFile = join(options.assets.base_dir, imageFile);
ensureDirSync(dirname(outputFile));
const data = attachment[mimeType];
// get the data
const imageText = Array.isArray(data)
? (data as string[]).join("")
: data as string;
// base 64 decode if its not svg
if (!imageText.trimStart().startsWith("<svg")) {
const imageData = base64decode(imageText);
Deno.writeFileSync(outputFile, imageData);
} else {
Deno.writeTextFileSync(outputFile, imageText);
}
// replace it in source
for (let i = 0; i < source.length; i++) {
source[i] = source[i].replaceAll(
`attachment:${file}`,
imageFile,