Line data Source code
1 : /** 2 : * INFO: Tools to parse Jupyter notebooks 3 : */ 4 : 5 : interface JupyterCell { 6 : cell_type: string, 7 : id: string, 8 : metadata: any, 9 : source?: string[], 10 : execution_count?: number, 11 : outputs: any[] 12 : } 13 : 14 : interface JupyterMetadata { 15 : kernelspec: any 16 : } 17 : 18 : interface JupyterSource { 19 : cells: JupyterCell[] 20 : metadata: JupyterMetadata 21 : } 22 : 23 1 : export class JupyterNotebook { 24 0 : get imageFolder(): string { 25 0 : return this._imageFolder; 26 0 : } 27 1 : get images(): { [p: string]: string } { 28 2 : return this._images; 29 1 : } 30 : private content: JupyterSource; 31 2 : private _images: { [key: string]: string } = {} 32 : private readonly imagePrefix: string 33 : private readonly _imageFolder: string 34 : private readonly language: string 35 1 : constructor(content: JupyterSource, 36 1 : imageFolder = "./images/", 37 1 : imagePrefix = "notebook_image") { 38 2 : this.content = content; 39 2 : this._imageFolder = imageFolder 40 2 : this.imagePrefix = imagePrefix 41 2 : this.language = content.metadata.kernelspec.language 42 1 : } 43 : 44 1 : render(): string { 45 2 : let lines: string[] = []; 46 2 : let imageCounter = 1; 47 2 : for (let cell of this.content.cells) { 48 20 : if (cell.cell_type == "markdown") { 49 26 : lines.push(cell.source!.join("")); 50 20 : } 51 20 : if (cell.cell_type == "code") { 52 32 : lines.push("```" + this.language) 53 32 : lines.push(cell.source!.join("")) 54 32 : lines.push("```\n") 55 : // now get the outputs 56 32 : for (let output of cell.outputs) { 57 38 : if (output.output_type == "display_data") { 58 40 : const data = output.data 59 40 : if ("image/png" in data) { 60 40 : const imageName = `${this.imagePrefix}_${imageCounter}` 61 40 : this._images[imageName] = data["image/png"] 62 40 : lines.push(`![${imageName}](${this._imageFolder}${imageName}.png)`) 63 40 : imageCounter += 1 64 40 : } 65 38 : } else if (output.output_type == "stream") { 66 44 : lines.push("```") 67 44 : lines.push(output.text.join("")) 68 44 : lines.push("```\n") 69 44 : } else if (output.output_type == "execute_result") { 70 44 : const data = output.data 71 44 : if (data["text/html"]) { 72 44 : lines.push(data["text/html"].join("")) 73 44 : } 74 38 : } 75 32 : } 76 20 : } 77 2 : } 78 2 : return lines.join("\n") 79 1 : } 80 1 : }