-
Notifications
You must be signed in to change notification settings - Fork 347
/
Copy pathjupyter.ts
240 lines (212 loc) · 6.11 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
/*
* jupyter.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import { stringify } from "yaml/mod.ts";
import {
partitionYamlFrontMatter,
readYamlFromMarkdown,
} from "../../core/yaml.ts";
import { kCellId, kCellLabel } from "../../config/constants.ts";
import { JupyterCell, JupyterCellOptions } from "../../core/jupyter/types.ts";
import {
jupyterAutoIdentifier,
jupyterCellOptionsAsComment,
jupyterCellWithOptions,
jupyterFromFile,
mdEnsureTrailingNewline,
mdFromContentCell,
mdFromRawCell,
quartoMdToJupyter,
} from "../../core/jupyter/jupyter.ts";
import { partitionCellOptions } from "../../core/lib/partition-cell-options.ts";
import { Metadata } from "../../config/types.ts";
import { jupyterKernelspec } from "../../core/jupyter/kernels.ts";
import { fixupFrontMatter } from "../../core/jupyter/jupyter-fixups.ts";
import {
jupyterCellSrcAsLines,
jupyterCellSrcAsStr,
} from "../../core/jupyter/jupyter-shared.ts";
export async function markdownToJupyterNotebook(
file: string,
includeIds: boolean,
) {
const markdown = Deno.readTextFileSync(file);
const notebook = await quartoMdToJupyter(markdown, includeIds);
return JSON.stringify(notebook, null, 2);
}
export async function jupyterNotebookToMarkdown(
file: string,
includeIds: boolean,
) {
// read notebook & alias kernelspec
const notebook = fixupFrontMatter(jupyterFromFile(file));
const kernelspec = notebook.metadata.kernelspec;
// generate markdown
const md: string[] = [];
let frontMatter: string | undefined;
for (let i = 0; i < notebook.cells.length; i++) {
{
// alias cell
const cell = notebook.cells[i];
const cellWithOptions = jupyterCellWithOptions(
i,
kernelspec.language,
cell,
);
// write markdown
switch (cell.cell_type) {
case "markdown":
md.push(...mdFromContentCell(cellWithOptions));
break;
case "raw":
// see if this is the front matter
if (frontMatter === undefined) {
frontMatter = partitionYamlFrontMatter(
jupyterCellSrcAsStr(cell),
)?.yaml;
if (!frontMatter) {
md.push(...mdFromRawCell(cellWithOptions));
}
} else {
md.push(...mdFromRawCell(cellWithOptions));
}
break;
case "code":
md.push(
...(await mdFromCodeCell(
kernelspec.language.toLowerCase(),
cell,
includeIds,
)),
);
break;
default:
throw new Error("Unexpected cell type " + cell.cell_type);
}
// if we didn't capture frontMatter then add a newline
if (i > 0 || !frontMatter) {
md.push("\n");
}
}
}
// join into source
const mdSource = md.join("");
// read any yaml front matter defined in a 'raw' cell
const yaml: Metadata = frontMatter ? readYamlFromMarkdown(frontMatter) : {};
// forward qmd-relevant notebook metadata. known metadata we exclude:
// - toc: Jupyter UI specific metadata
// - language_info: Jupyter UI specific metadata
// - widgets: Output artifacts that don't belong in qmd source
// for jupytext we provide a full kernelspec + jupytext metadata,
// otherwise we provide an abbreviated spec w/ just the kernel name
yaml.jupyter = notebook.metadata.jupytext
? {
jupytext: notebook.metadata.jupytext,
kernelspec: notebook.metadata.kernelspec,
}
: notebook.metadata.kernelspec.name;
// if we are using the string shorthand make sure we have this kernelspec locally
if (typeof yaml.jupyter === "string") {
if (!await jupyterKernelspec(yaml.jupyter)) {
yaml.jupyter = {
kernelspec: notebook.metadata.kernelspec,
};
}
}
// return yaml + markdown
const yamlText = stringify(yaml, {
indent: 2,
lineWidth: -1,
sortKeys: false,
skipInvalid: true,
});
return `---\n${yamlText}---\n\n${mdSource}`;
}
async function mdFromCodeCell(
language: string,
cell: JupyterCell,
includeIds: boolean,
) {
// redact if the cell has no source
if (!cell.source.length) {
return [];
}
// determine the largest number of backticks in the cell
const maxBackticks = Math.max(
...jupyterCellSrcAsLines(cell).map((line) =>
line.match(/^`+/g)?.[0].length || 0
),
2,
);
const backticks = "`".repeat(maxBackticks + 1);
// begin code cell
const md: string[] = [backticks + "{" + language + "}\n"];
// partition
const { yaml, source } = await partitionCellOptions(
language,
jupyterCellSrcAsLines(cell),
);
const options = yaml ? yaml as JupyterCellOptions : {};
if (!includeIds) {
delete cell.id;
delete cell.metadata["id"];
delete cell.metadata["outputId"];
} else {
if (cell.id) {
if (options[kCellLabel]) {
const label = String(options[kCellLabel]);
if (jupyterAutoIdentifier(label) === cell.id) {
cell.id = undefined;
}
}
}
}
// prepare the options for writing
let yamlOptions: Metadata = {};
if (cell.id) {
yamlOptions[kCellId] = cell.id;
}
yamlOptions = {
...cell.metadata,
...yaml,
...yamlOptions,
};
// cell id first
if (yamlOptions[kCellId]) {
md.push(
...jupyterCellOptionsAsComment(language, { id: yamlOptions[kCellId] }),
);
delete yamlOptions[kCellId];
}
// yaml
if (yaml) {
const yamlOutput: Metadata = {};
for (const key in yaml) {
const value = yamlOptions[key];
if (value !== undefined) {
yamlOutput[key] = value;
delete yamlOptions[key];
}
}
md.push(...jupyterCellOptionsAsComment(language, yamlOutput));
}
// metadata
const metadataOutput: Metadata = {};
for (const key in cell.metadata) {
const value = cell.metadata[key];
if (value !== undefined) {
metadataOutput[key] = value;
delete yamlOptions[key];
}
}
md.push(
...jupyterCellOptionsAsComment(language, metadataOutput, { flowLevel: 1 }),
);
// write cell code
md.push(...mdEnsureTrailingNewline(source));
// end code cell
md.push(backticks + "\n");
return md;
}