Coverage for pyquickhelper/helpgen/process_notebook_api.py: 82%
96 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
1# -*- coding: utf-8 -*-
2"""
3@file
4@brief Direct calls to IPython API without running a command line
5"""
6import os
7from .utils_sphinx_doc_helpers import HelpGenException
10def get_exporter(format, add_writer=False):
11 """
12 Returns the :epkg:`IPython` exporter associated to a format.
14 @param format string (see below)
15 @param add_writer add writer as well
16 @return class
18 Available formats: *slides*, *pdf*, *latex*, *markdown*, *html*,
19 *rst*, *python*, *notebook*, *template*.
20 """
21 if format == "python":
22 from nbconvert import PythonExporter
23 exp = PythonExporter
24 elif format == "slides":
25 from nbconvert import SlidesExporter
26 exp = SlidesExporter
27 elif format == "html":
28 from nbconvert import HTMLExporter
29 exp = HTMLExporter
30 elif format == "pdf":
31 from nbconvert import PDFExporter
32 exp = PDFExporter
33 elif format == "template":
34 from nbconvert import TemplateExporter
35 exp = TemplateExporter
36 elif format == "markdown":
37 from nbconvert import MarkdownExporter
38 exp = MarkdownExporter
39 elif format == "notebook":
40 from nbconvert import NotebookExporter
41 exp = NotebookExporter
42 elif format == "rst":
43 from .notebook_exporter import UpgradedRSTExporter
44 exp = UpgradedRSTExporter
45 elif format == "lagex":
46 from nbconvert import LatexExporter
47 exp = LatexExporter
48 else:
49 form = "slides, pdf, latex, markdown, html, rst, python, notebook, template"
50 raise ValueError( # pragma: no cover
51 f"unexpected format: {format}, it should be in:\n{form}")
53 if add_writer:
54 from nbconvert.writers import FilesWriter
55 return exp, FilesWriter
56 return exp
59def nb2slides(nb_file, outfile, add_tag=True):
60 """
61 Converts a notebook into slides, it copies
62 :epkg:`reveal.js` if not present in the folder of the output.
64 @param nb_file notebook file or a stream or a @see fn read_nb
65 @param outfile output file (a string)
66 @param add_tag call @see me add_tag_slide
67 @return impacted files
69 See `How do I convert a IPython Notebook into a Python file via commandline?
70 <http://stackoverflow.com/questions/17077494/how-do-i-convert-a-ipython-notebook-into-a-python-file-via-commandline>`_
72 .. exref::
73 :title: Convert a notebook into slides
75 By default, the function automatically adds sections if there is none
76 and it copies the javascript from reveal.js at the right place.
78 ::
80 from pyquickhelper.helpgen import nb2slides
81 nb2slides("nb.ipynb", "convert.slides.html")
82 """
83 from ..ipythonhelper import NotebookRunner, read_nb
84 from .post_process import post_process_slides_output
86 if isinstance(nb_file, NotebookRunner):
87 nb = nb_file.nb
88 else:
89 nbr = read_nb(nb_file, kernel=False)
90 nb = nbr.nb
92 if add_tag:
93 run = NotebookRunner(nb, kernel=False)
94 run.add_tag_slide()
95 nb = run.nb
97 exporter = get_exporter("slides")()
98 source = exporter.from_notebook_node(nb)[0]
100 with open(outfile, 'w+', encoding="utf8") as fh:
101 fh.writelines(source)
103 # post_processing
104 post_process_slides_output(outfile, False, False, False, False)
105 res = [outfile]
107 # we copy javascript dependencies, reveal.js
108 dirname = os.path.dirname(outfile)
109 reveal = os.path.join(dirname, "reveal.js")
110 if not os.path.exists(reveal):
111 from .install_js_dep import install_javascript_tools
112 cp = install_javascript_tools(None, dest=dirname)
113 res.extend(cp)
115 return res
118def nb2html(nb_file, outfile, exc=True):
119 """
120 Converts a notebook into HTML.
122 @param nb_file notebook file or a stream or a @see fn read_nb
123 @param outfile output file (a string)
124 @param exc raises an exception (True) or a warning (False)
125 @return impacted files
126 """
127 from ..ipythonhelper import NotebookRunner, read_nb
129 if isinstance(nb_file, NotebookRunner):
130 nb = nb_file.nb
131 else:
132 nbr = read_nb(nb_file, kernel=False)
133 nb = nbr.nb
135 exporter = get_exporter("html")()
136 source = exporter.from_notebook_node(nb)[0]
138 with open(outfile, 'w+', encoding="utf8") as fh:
139 fh.writelines(source)
141 # post_processing
142 from .post_process import post_process_html_output
143 post_process_html_output(outfile, False, False, False, exc=exc)
144 res = [outfile]
145 return res
148def nb2rst(nb_file, outfile, exc=True, post_process=True):
149 """
150 Converts a notebook into :epkg:`RST`.
152 @param nb_file notebook file or a stream or a @see fn read_nb
153 @param outfile output file (a string)
154 @param exc raises an exception (True) or a warning (False)
155 @param post_process calls @see fn post_process_rst_output
156 @return impacted files
157 """
158 from ..ipythonhelper import NotebookRunner, read_nb
160 if isinstance(nb_file, NotebookRunner):
161 nb = nb_file.nb
162 else:
163 nbr = read_nb(nb_file, kernel=False)
164 nb = nbr.nb
166 exp_class, writer_class = get_exporter("rst", add_writer=True)
167 exporter = exp_class()
168 writer = writer_class()
169 unique_key = os.path.splitext(os.path.split(outfile)[-1])[0]
170 source, meta = exporter.from_notebook_node(
171 nb, resources=dict(unique_key=unique_key))
173 name, ext = os.path.splitext(outfile)
174 if ext != '.rst':
175 raise ValueError( # pragma: no cover
176 f"'{outfile}' should have extension '.rst'")
177 writer.build_directory = os.path.dirname(outfile)
178 writer.write(source, meta, notebook_name=name)
180 # post_processing
181 if post_process:
182 from .post_process import post_process_rst_output
183 try:
184 post_process_rst_output(outfile, False, False,
185 False, False, False, exc=exc)
186 except HelpGenException as e:
187 raise HelpGenException( # pragma: no cover
188 "Unable to postprocess notebook '{}' with writer '{}' and "
189 "exporter '{}'".format(
190 getattr(nb_file, '_filename', nb_file),
191 type(writer), type(exporter))) from e
193 res = [outfile]
194 return res