File size: 7,956 Bytes
d1ceb73 |
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 |
"""Read and write notebooks as regular .py files.
Authors:
* Brian Granger
"""
# -----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file LICENSE, distributed as part of this software.
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
from __future__ import annotations
import re
from .nbbase import (
nbformat,
nbformat_minor,
new_code_cell,
new_heading_cell,
new_notebook,
new_text_cell,
new_worksheet,
)
from .rwbase import NotebookReader, NotebookWriter
# -----------------------------------------------------------------------------
# Code
# -----------------------------------------------------------------------------
_encoding_declaration_re = re.compile(r"^#.*coding[:=]\s*([-\w.]+)")
class PyReaderError(Exception):
"""An error raised for a pyreader error."""
class PyReader(NotebookReader):
"""A python notebook reader."""
def reads(self, s, **kwargs):
"""Convert a string to a notebook"""
return self.to_notebook(s, **kwargs)
def to_notebook(self, s, **kwargs):
"""Convert a string to a notebook"""
lines = s.splitlines()
cells = []
cell_lines: list[str] = []
kwargs = {}
state = "codecell"
for line in lines:
if line.startswith("# <nbformat>") or _encoding_declaration_re.match(line):
pass
elif line.startswith("# <codecell>"):
cell = self.new_cell(state, cell_lines, **kwargs)
if cell is not None:
cells.append(cell)
state = "codecell"
cell_lines = []
kwargs = {}
elif line.startswith("# <htmlcell>"):
cell = self.new_cell(state, cell_lines, **kwargs)
if cell is not None:
cells.append(cell)
state = "htmlcell"
cell_lines = []
kwargs = {}
elif line.startswith("# <markdowncell>"):
cell = self.new_cell(state, cell_lines, **kwargs)
if cell is not None:
cells.append(cell)
state = "markdowncell"
cell_lines = []
kwargs = {}
# VERSIONHACK: plaintext -> raw
elif line.startswith(("# <rawcell>", "# <plaintextcell>")):
cell = self.new_cell(state, cell_lines, **kwargs)
if cell is not None:
cells.append(cell)
state = "rawcell"
cell_lines = []
kwargs = {}
elif line.startswith("# <headingcell"):
cell = self.new_cell(state, cell_lines, **kwargs)
if cell is not None:
cells.append(cell)
cell_lines = []
m = re.match(r"# <headingcell level=(?P<level>\d)>", line)
if m is not None:
state = "headingcell"
kwargs = {}
kwargs["level"] = int(m.group("level"))
else:
state = "codecell"
kwargs = {}
cell_lines = []
else:
cell_lines.append(line)
if cell_lines and state == "codecell":
cell = self.new_cell(state, cell_lines)
if cell is not None:
cells.append(cell)
ws = new_worksheet(cells=cells)
return new_notebook(worksheets=[ws])
def new_cell(self, state, lines, **kwargs):
"""Create a new cell."""
if state == "codecell":
input_ = "\n".join(lines)
input_ = input_.strip("\n")
if input_:
return new_code_cell(input=input_)
elif state == "htmlcell":
text = self._remove_comments(lines)
if text:
return new_text_cell("html", source=text)
elif state == "markdowncell":
text = self._remove_comments(lines)
if text:
return new_text_cell("markdown", source=text)
elif state == "rawcell":
text = self._remove_comments(lines)
if text:
return new_text_cell("raw", source=text)
elif state == "headingcell":
text = self._remove_comments(lines)
level = kwargs.get("level", 1)
if text:
return new_heading_cell(source=text, level=level)
def _remove_comments(self, lines):
new_lines = []
for line in lines:
if line.startswith("#"):
new_lines.append(line[2:])
else:
new_lines.append(line)
text = "\n".join(new_lines)
text = text.strip("\n")
return text # noqa: RET504
def split_lines_into_blocks(self, lines):
"""Split lines into code blocks."""
if len(lines) == 1:
yield lines[0]
raise StopIteration()
import ast
source = "\n".join(lines)
code = ast.parse(source)
starts = [x.lineno - 1 for x in code.body]
for i in range(len(starts) - 1):
yield "\n".join(lines[starts[i] : starts[i + 1]]).strip("\n")
yield "\n".join(lines[starts[-1] :]).strip("\n")
class PyWriter(NotebookWriter):
"""A Python notebook writer."""
def writes(self, nb, **kwargs):
"""Convert a notebook to a string."""
lines = ["# -*- coding: utf-8 -*-"]
lines.extend(
[
"# <nbformat>%i.%i</nbformat>" % (nbformat, nbformat_minor),
"",
]
)
for ws in nb.worksheets:
for cell in ws.cells:
if cell.cell_type == "code":
input_ = cell.get("input")
if input_ is not None:
lines.extend(["# <codecell>", ""])
lines.extend(input_.splitlines())
lines.append("")
elif cell.cell_type == "html":
input_ = cell.get("source")
if input_ is not None:
lines.extend(["# <htmlcell>", ""])
lines.extend(["# " + line for line in input_.splitlines()])
lines.append("")
elif cell.cell_type == "markdown":
input_ = cell.get("source")
if input_ is not None:
lines.extend(["# <markdowncell>", ""])
lines.extend(["# " + line for line in input_.splitlines()])
lines.append("")
elif cell.cell_type == "raw":
input_ = cell.get("source")
if input_ is not None:
lines.extend(["# <rawcell>", ""])
lines.extend(["# " + line for line in input_.splitlines()])
lines.append("")
elif cell.cell_type == "heading":
input_ = cell.get("source")
level = cell.get("level", 1)
if input_ is not None:
lines.extend(["# <headingcell level=%s>" % level, ""])
lines.extend(["# " + line for line in input_.splitlines()])
lines.append("")
lines.append("")
return "\n".join(lines)
_reader = PyReader()
_writer = PyWriter()
reads = _reader.reads
read = _reader.read
to_notebook = _reader.to_notebook
write = _writer.write
writes = _writer.writes
|