11"""Manipulating the Sphinx AST with Jupyter objects"""
22
3- import os
43import json
5- import contextlib
64from pathlib import Path
75
86import docutils
7+ import ipywidgets .embed
8+ import nbconvert
9+ from docutils .nodes import literal , math_block
910from docutils .parsers .rst import Directive , directives
10- from docutils .nodes import math_block , image , literal
11- from sphinx .util import parselinenos
12- from sphinx .util .docutils import ReferenceRole
1311from sphinx .addnodes import download_reference
14- from sphinx .transforms import SphinxTransform
15- from sphinx .environment .collectors .asset import ImageCollector
1612from sphinx .errors import ExtensionError
13+ from sphinx .transforms import SphinxTransform
14+ from sphinx .util import parselinenos
15+ from sphinx .util .docutils import ReferenceRole
1716
18- import ipywidgets .embed
19- import nbconvert
20-
21- from .utils import strip_latex_delimiters , sphinx_abs_dir
22- from .thebelab import ThebeSourceNode , ThebeOutputNode
17+ from .thebelab import ThebeOutputNode , ThebeSourceNode
18+ from .utils import sphinx_abs_dir , strip_latex_delimiters
2319
2420WIDGET_VIEW_MIMETYPE = "application/vnd.jupyter.widget-view+json"
2521WIDGET_STATE_MIMETYPE = "application/vnd.jupyter.widget-state+json"
@@ -45,8 +41,8 @@ def load_content(cell, location, logger):
4541 try :
4642 with Path (filename ).open () as f :
4743 content = [line .rstrip () for line in f .readlines ()]
48- except ( IOError , OSError ) :
49- raise IOError ( "File {} not found or reading it failed" . format ( filename ) )
44+ except OSError :
45+ raise OSError ( f "File { filename } not found or reading it failed" )
5046 else :
5147 cell .assert_has_content ()
5248 content = cell .content
@@ -165,6 +161,7 @@ def run(self):
165161 cell_node += cell_input
166162 return [cell_node ]
167163
164+
168165class CellInput (Directive ):
169166 """Define a code cell to be included verbatim but not executed.
170167
@@ -182,7 +179,7 @@ class CellInput(Directive):
182179 specified line.
183180 emphasize-lines : comma separated list of line numbers
184181 If provided, the specified lines will be highlighted.
185-
182+
186183 Content
187184 -------
188185 code : str
@@ -235,6 +232,7 @@ def run(self):
235232 cell_node += cell_input
236233 return [cell_node ]
237234
235+
238236class CellOutput (Directive ):
239237 """Define an output cell to be included verbatim.
240238
@@ -328,14 +326,14 @@ def render_as(self, visitor):
328326 try :
329327 # Or should we go to config via the node?
330328 priority = visitor .builder .env .app .config [
331- ' render_priority_' + visitor .builder .format
329+ " render_priority_" + visitor .builder .format
332330 ]
333331 except (AttributeError , KeyError ):
334332 # Not sure what do to, act as a container and show everything just in case.
335333 return super ()
336334 for mimetype in priority :
337335 try :
338- return self .children [self .attributes [' mimetypes' ].index (mimetype )]
336+ return self .children [self .attributes [" mimetypes" ].index (mimetype )]
339337 except ValueError :
340338 pass
341339 # Same
@@ -388,19 +386,19 @@ def __init__(self, rawsource="", *children, **attributes):
388386 super ().__init__ ("" , state = attributes ["state" ])
389387
390388 def html (self ):
391-
392- # escape </script> to avoid early closing of the tag in the html page
389+
390+ # escape </script> to avoid early closing of the tag in the html page
393391 json_data = json .dumps (self ["state" ]).replace ("</script>" , r"<\/script>" )
394-
392+
395393 # TODO: render into a separate file if 'html-manager' starts fully
396394 # parsing script tags, and not just grabbing their innerHTML
397395 # https://github.com/jupyter-widgets/ipywidgets/blob/master/packages/html-manager/src/libembed.ts#L36
398396 return ipywidgets .embed .snippet_template .format (
399397 load = "" , widget_views = "" , json_data = json_data
400398 )
401399
402- def cell_output_to_nodes ( outputs , write_stderr , out_dir ,
403- thebe_config , inline = False ):
400+
401+ def cell_output_to_nodes ( outputs , write_stderr , out_dir , thebe_config , inline = False ):
404402 """Convert a jupyter cell with outputs and filenames to doctree nodes.
405403
406404 Parameters
@@ -476,11 +474,8 @@ def cell_output_to_nodes(outputs, write_stderr, out_dir,
476474 )
477475 elif output_type in ("display_data" , "execute_result" ):
478476 children_by_mimetype = {
479- mime_type : output2sphinx (
480- data , mime_type , output ["metadata" ], out_dir
481- )
477+ mime_type : output2sphinx (data , mime_type , output ["metadata" ], out_dir )
482478 for mime_type , data in output ["data" ].items ()
483-
484479 }
485480 # Filter out unknown mimetypes
486481 # TODO: rewrite this using walrus once we depend on Python 3.8
@@ -489,11 +484,13 @@ def cell_output_to_nodes(outputs, write_stderr, out_dir,
489484 for mime_type , node in children_by_mimetype .items ()
490485 if node is not None
491486 }
492- to_add .append (MimeBundleNode (
493- "" ,
494- * list (children_by_mimetype .values ()),
495- mimetypes = list (children_by_mimetype .keys ())
496- ))
487+ to_add .append (
488+ MimeBundleNode (
489+ "" ,
490+ * list (children_by_mimetype .values ()),
491+ mimetypes = list (children_by_mimetype .keys ()),
492+ )
493+ )
497494
498495 return to_add
499496
@@ -552,7 +549,7 @@ def output2sphinx(data, mime_type, metadata, out_dir, inline=False):
552549 uri = (out_dir / filename ).as_posix ()
553550 return docutils .nodes .image (uri = uri )
554551 else :
555- logger .debug (f' Unknown mime type in cell output: { mime_type } ' )
552+ logger .debug (f" Unknown mime type in cell output: { mime_type } " )
556553
557554
558555def apply_styling (node , thebe_config ):
@@ -621,14 +618,14 @@ def apply(self):
621618 moved_outputs = set ()
622619
623620 for cell_node in self .document .traverse (JupyterCellNode ):
624- if cell_node .attributes ["execute" ] == False :
625- if cell_node .attributes ["hide_code" ] == False :
621+ if not cell_node .attributes ["execute" ]:
622+ if not cell_node .attributes ["hide_code" ]:
626623 # Cell came from jupyter-input
627624 sibling = cell_node .next_node (descend = False , siblings = True )
628625 if (
629626 isinstance (sibling , JupyterCellNode )
630- and sibling .attributes ["execute" ] == False
631- and sibling .attributes ["hide_code" ] == True
627+ and not sibling .attributes ["execute" ]
628+ and sibling .attributes ["hide_code" ]
632629 ):
633630 # Sibling came from jupyter-output, so we merge
634631 cell_node += sibling .children [1 ]
0 commit comments