or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdcustom-directives.mdindex.mdnotebook-processing.mdsphinx-extension.mdtext-processing.md

notebook-processing.mddocs/

0

# Notebook Processing

1

2

Core functionality for converting Jupyter notebooks to reStructuredText with support for execution, custom templates, and resource management. This module handles the parsing and transformation of notebook content for Sphinx documentation generation.

3

4

## Capabilities

5

6

### Notebook Export

7

8

Converts Jupyter notebooks to reStructuredText using nbconvert with custom templates and execution support.

9

10

```python { .api }

11

class Exporter(nbconvert.RSTExporter):

12

"""

13

Convert Jupyter notebooks to reStructuredText.

14

15

Uses nbconvert to convert Jupyter notebooks to a reStructuredText

16

string with custom reST directives for input and output cells.

17

Notebooks without output cells are automatically executed before conversion.

18

"""

19

20

def __init__(self, execute='auto', kernel_name='', execute_arguments=[],

21

allow_errors=False, timeout=None, codecell_lexer='none'):

22

"""

23

Initialize the Exporter.

24

25

Parameters:

26

- execute: str, execution mode ('auto', 'always', 'never')

27

- kernel_name: str, Jupyter kernel name for execution

28

- execute_arguments: list, arguments for kernel execution

29

- allow_errors: bool, allow errors during execution

30

- timeout: int, execution timeout in seconds

31

- codecell_lexer: str, syntax highlighter for code cells

32

"""

33

34

def from_notebook_node(self, nb, resources=None, **kw):

35

"""

36

Convert notebook node to RST string with resources.

37

38

Parameters:

39

- nb: NotebookNode, notebook to convert

40

- resources: dict, conversion resources and metadata

41

- **kw: additional keyword arguments

42

43

Returns:

44

tuple: (rststring, resources) - converted RST and updated resources

45

"""

46

```

47

48

Usage example:

49

50

```python

51

from nbsphinx import Exporter

52

import nbformat

53

54

# Load notebook

55

with open('example.ipynb', 'r') as f:

56

nb = nbformat.read(f, as_version=4)

57

58

# Create exporter with custom settings

59

exporter = Exporter(

60

execute='auto',

61

allow_errors=False,

62

timeout=30,

63

codecell_lexer='python'

64

)

65

66

# Convert notebook

67

rststring, resources = exporter.from_notebook_node(nb)

68

print(rststring) # Converted reStructuredText

69

```

70

71

### Notebook Parsing

72

73

Sphinx source parser that integrates notebooks into the Sphinx build system with custom format support.

74

75

```python { .api }

76

class NotebookParser(rst.Parser):

77

"""

78

Sphinx source parser for Jupyter notebooks.

79

80

Uses nbsphinx.Exporter to convert notebook content to a

81

reStructuredText string, which is then parsed by Sphinx's built-in

82

reST parser.

83

"""

84

85

supported = ('jupyter_notebook',)

86

87

def get_transforms(self):

88

"""List of transforms for documents parsed by this parser."""

89

90

def parse(self, inputstring, document):

91

"""

92

Parse *inputstring*, write results to *document*.

93

94

Parameters:

95

- inputstring: str, JSON representation of notebook or text from translation

96

- document: docutils document node to populate

97

98

Notes:

99

- If nbsphinx_custom_formats is specified, input is converted to notebook format

100

- Supports custom conversion functions for different file formats

101

- Automatically executes notebooks based on configuration

102

- Handles resource management for output files and images

103

"""

104

```

105

106

Usage is automatic when files with `.ipynb` extension are processed by Sphinx.

107

108

### Thumbnail Extraction

109

110

Functionality for extracting and managing thumbnail images from notebook outputs for gallery displays.

111

112

```python { .api }

113

def _extract_thumbnail(cell, output_index):

114

"""

115

Extract thumbnail from notebook cell output.

116

117

Parameters:

118

- cell: NotebookNode, notebook cell with outputs

119

- output_index: int, index of output to extract from

120

121

Returns:

122

str: File extension for extracted thumbnail

123

124

Raises:

125

_ExtractThumbnailException: If thumbnail cannot be extracted

126

"""

127

128

class _ExtractThumbnailException(Exception):

129

"""

130

Internal exception thrown by _extract_thumbnail().

131

132

Raised when thumbnail extraction fails due to missing or

133

incompatible output data in notebook cells.

134

"""

135

```

136

137

Usage example:

138

139

```python

140

# Thumbnail extraction is handled automatically during conversion

141

# Can be controlled via notebook metadata:

142

143

# In notebook cell metadata:

144

{

145

"nbsphinx-thumbnail": {

146

"output-index": 0,

147

"tooltip": "Custom tooltip text"

148

}

149

}

150

151

# Or via cell tags:

152

{

153

"tags": ["nbsphinx-thumbnail"]

154

}

155

```

156

157

### Error Handling

158

159

Custom exception types for notebook processing errors.

160

161

```python { .api }

162

class NotebookError(sphinx.errors.SphinxError):

163

"""

164

Error during notebook parsing.

165

166

Attributes:

167

- category: str, error category ('Notebook error')

168

"""

169

```

170

171

Usage example:

172

173

```python

174

try:

175

# Notebook processing code

176

rststring, resources = exporter.from_notebook_node(nb)

177

except NotebookError as e:

178

print(f"Notebook processing failed: {e}")

179

# Handle error appropriately

180

```

181

182

## Template System

183

184

The notebook conversion uses a custom RST template that defines how different notebook elements are rendered:

185

186

- **Input cells**: Converted to `nbinput` directives with syntax highlighting

187

- **Output cells**: Converted to `nboutput` directives with format-specific handling

188

- **Markdown cells**: Converted to standard RST with attachment support

189

- **Raw cells**: Handled based on MIME type (HTML, LaTeX, RST, etc.)

190

- **Metadata**: Processed for execution control, thumbnails, and gallery features

191

192

The template system allows customization of the conversion process while maintaining compatibility with Sphinx's RST processing pipeline.