content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
\n\n | .venv\Lib\site-packages\nbclient\__pycache__\output_widget.cpython-313.pyc | output_widget.cpython-313.pyc | Other | 6,061 | 0.95 | 0.036364 | 0 | node-utils | 255 | 2023-11-05T12:21:42.481084 | Apache-2.0 | false | c3143fc7d73741c59485a53c43965ce0 |
\n\n | .venv\Lib\site-packages\nbclient\__pycache__\util.cpython-313.pyc | util.cpython-313.pyc | Other | 860 | 0.8 | 0 | 0 | python-kit | 927 | 2025-05-08T01:32:52.882545 | BSD-3-Clause | false | ad616f16c2e7d1ef7fca666674ffd7d2 |
\n\n | .venv\Lib\site-packages\nbclient\__pycache__\_version.cpython-313.pyc | _version.cpython-313.pyc | Other | 826 | 0.8 | 0 | 0 | react-lib | 777 | 2025-05-06T04:53:06.349072 | Apache-2.0 | false | b32dabfbca1cc36c739ef49f49493e75 |
\n\n | .venv\Lib\site-packages\nbclient\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 361 | 0.7 | 0 | 0 | vue-tools | 789 | 2024-12-22T17:31:01.379827 | GPL-3.0 | false | 08dcf118206f41490249d68a0f59f534 |
[console_scripts]\njupyter-execute = nbclient.cli:main\n | .venv\Lib\site-packages\nbclient-0.10.2.dist-info\entry_points.txt | entry_points.txt | Other | 54 | 0.5 | 0 | 0 | python-kit | 990 | 2025-04-20T09:13:57.548021 | GPL-3.0 | false | aef15fdbfdfc8a304debf3d99f4d8225 |
pip\n | .venv\Lib\site-packages\nbclient-0.10.2.dist-info\INSTALLER | INSTALLER | Other | 4 | 0.5 | 0 | 0 | node-utils | 463 | 2023-07-31T16:27:35.040561 | BSD-3-Clause | false | 365c9bfeb7d89244f2ce01c1de44cb85 |
Metadata-Version: 2.4\nName: nbclient\nVersion: 0.10.2\nSummary: A client library for executing notebooks. Formerly nbconvert's ExecutePreprocessor.\nProject-URL: Documentation, https://nbclient.readthedocs.io\nProject-URL: Funding, https://numfocus.org/\nProject-URL: Homepage, https://jupyter.org\nProject-URL: Source, https://github.com/jupyter/nbclient\nProject-URL: Tracker, https://github.com/jupyter/nbclient/issues\nAuthor-email: Jupyter Development Team <jupyter@googlegroups.com>\nLicense: BSD 3-Clause License\n \n Copyright (c) 2020-, Jupyter Development Team\n \n All rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n \n 1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n \n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n \n 3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nLicense-File: LICENSE\nKeywords: executor,jupyter,notebook,pipeline\nClassifier: Intended Audience :: Developers\nClassifier: Intended Audience :: Science/Research\nClassifier: Intended Audience :: System Administrators\nClassifier: License :: OSI Approved :: BSD License\nClassifier: Programming Language :: Python\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nClassifier: Programming Language :: Python :: 3.12\nClassifier: Programming Language :: Python :: 3.13\nRequires-Python: >=3.9.0\nRequires-Dist: jupyter-client>=6.1.12\nRequires-Dist: jupyter-core!=5.0.*,>=4.12\nRequires-Dist: nbformat>=5.1\nRequires-Dist: traitlets>=5.4\nProvides-Extra: dev\nRequires-Dist: pre-commit; extra == 'dev'\nProvides-Extra: docs\nRequires-Dist: autodoc-traits; extra == 'docs'\nRequires-Dist: flaky; extra == 'docs'\nRequires-Dist: ipykernel>=6.19.3; extra == 'docs'\nRequires-Dist: ipython; extra == 'docs'\nRequires-Dist: ipywidgets; extra == 'docs'\nRequires-Dist: mock; extra == 'docs'\nRequires-Dist: moto; extra == 'docs'\nRequires-Dist: myst-parser; extra == 'docs'\nRequires-Dist: nbconvert>=7.1.0; extra == 'docs'\nRequires-Dist: pytest-asyncio; extra == 'docs'\nRequires-Dist: pytest-cov>=4.0; extra == 'docs'\nRequires-Dist: pytest<8,>=7.0; extra == 'docs'\nRequires-Dist: sphinx-book-theme; extra == 'docs'\nRequires-Dist: sphinx>=1.7; extra == 'docs'\nRequires-Dist: sphinxcontrib-spelling; extra == 'docs'\nRequires-Dist: testpath; extra == 'docs'\nRequires-Dist: xmltodict; extra == 'docs'\nProvides-Extra: test\nRequires-Dist: flaky; extra == 'test'\nRequires-Dist: ipykernel>=6.19.3; extra == 'test'\nRequires-Dist: ipython; extra == 'test'\nRequires-Dist: ipywidgets; extra == 'test'\nRequires-Dist: nbconvert>=7.1.0; extra == 'test'\nRequires-Dist: pytest-asyncio; extra == 'test'\nRequires-Dist: pytest-cov>=4.0; extra == 'test'\nRequires-Dist: pytest<8,>=7.0; extra == 'test'\nRequires-Dist: testpath; extra == 'test'\nRequires-Dist: xmltodict; extra == 'test'\nDescription-Content-Type: text/markdown\n\n[](https://mybinder.org/v2/gh/jupyter/nbclient/main?filepath=binder%2Frun_nbclient.ipynb)\n[](https://github.com/jupyter/nbclient/actions)\n[](https://nbclient.readthedocs.io/en/latest/?badge=latest)\n[](https://www.python.org/downloads/release/python-370/)\n[](https://www.python.org/downloads/release/python-380/)\n[](https://www.python.org/downloads/release/python-390/)\n[](https://www.python.org/downloads/release/python-3100/)\n[](https://www.python.org/downloads/release/python-3110/)\n[](https://github.com/ambv/black)\n\n# nbclient\n\n**NBClient** lets you **execute** notebooks.\n\nA client library for programmatic notebook execution, **NBClient** is a tool for running Jupyter Notebooks in\ndifferent execution contexts, including the command line.\n\n## Interactive Demo\n\nTo demo **NBClient** interactively, click this Binder badge to start the demo:\n\n[](https://mybinder.org/v2/gh/jupyter/nbclient/main?filepath=binder%2Frun_nbclient.ipynb)\n\n## Installation\n\nIn a terminal, run:\n\n```\npython3 -m pip install nbclient\n```\n\n## Documentation\n\nSee [ReadTheDocs](https://nbclient.readthedocs.io/en/latest/) for more in-depth details about the project and the\n[API Reference](https://nbclient.readthedocs.io/en/latest/reference/index.html).\n\n## Python Version Support\n\nThis library currently supports Python 3.6+ versions. As minor Python\nversions are officially sunset by the Python org, nbclient will similarly\ndrop support in the future.\n\n## Origins\n\nThis library used to be part of the [nbconvert](https://nbconvert.readthedocs.io/en/latest/) project. NBClient extracted nbconvert's `ExecutePreprocessor`into its own library for easier updating and importing by downstream libraries and applications.\n\n## Relationship to JupyterClient\n\nNBClient and JupyterClient are distinct projects.\n\n`jupyter_client` is a client library for the jupyter protocol. Specifically, `jupyter_client` provides the Python API\nfor starting, managing and communicating with Jupyter kernels.\n\nWhile, nbclient allows notebooks to be run in different execution contexts.\n\n## About the Jupyter Development Team\n\nThe Jupyter Development Team is the set of all contributors to the Jupyter project.\nThis includes all of the Jupyter subprojects.\n\nThe core team that coordinates development on GitHub can be found here:\nhttps://github.com/jupyter/.\n\n## Our Copyright Policy\n\nJupyter uses a shared copyright model. Each contributor maintains copyright\nover their contributions to Jupyter. But, it is important to note that these\ncontributions are typically only changes to the repositories. Thus, the Jupyter\nsource code, in its entirety is not the copyright of any single person or\ninstitution. Instead, it is the collective copyright of the entire Jupyter\nDevelopment Team. If individual contributors want to maintain a record of what\nchanges/contributions they have specific copyright on, they should indicate\ntheir copyright in the commit message of the change, when they commit the\nchange to one of the Jupyter repositories.\n\nWith this in mind, the following banner should be used in any source code file\nto indicate the copyright and license terms:\n\n```\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n```\n | .venv\Lib\site-packages\nbclient-0.10.2.dist-info\METADATA | METADATA | Other | 8,263 | 0.95 | 0.040462 | 0.086331 | react-lib | 560 | 2024-01-26T06:39:28.217224 | MIT | false | 5fa6122fdb87cf45a504c24e7c19aa6c |
../../Scripts/jupyter-execute.exe,sha256=heOpg6eXYAAbwqtYs_vPelYR7EynDQIeuunExtRGrg8,108413\nnbclient-0.10.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\nnbclient-0.10.2.dist-info/METADATA,sha256=AgHaGDYAlNOBeiTo_-BlrwTXXodzUIN_YTLCAqElpKY,8263\nnbclient-0.10.2.dist-info/RECORD,,\nnbclient-0.10.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87\nnbclient-0.10.2.dist-info/entry_points.txt,sha256=sHJQnUBVokK46O2PK-g1WG9QAhTmaXy3fwshQ_t7TFA,54\nnbclient-0.10.2.dist-info/licenses/LICENSE,sha256=g8VsLeKipxIn0KmP0kYEnmMgwJTQPi1WDHwMCz7Fduk,1534\nnbclient/__init__.py,sha256=kOkox4riED023V62iBDJMKbI1VcH3LM6VERaX9l6v6c,164\nnbclient/__pycache__/__init__.cpython-313.pyc,,\nnbclient/__pycache__/_version.cpython-313.pyc,,\nnbclient/__pycache__/cli.cpython-313.pyc,,\nnbclient/__pycache__/client.cpython-313.pyc,,\nnbclient/__pycache__/exceptions.cpython-313.pyc,,\nnbclient/__pycache__/jsonutil.cpython-313.pyc,,\nnbclient/__pycache__/output_widget.cpython-313.pyc,,\nnbclient/__pycache__/util.cpython-313.pyc,,\nnbclient/_version.py,sha256=Is9ur6poRQor3aJ9NVAjRbJKzjjJPGDme4jZnTB1S2M,463\nnbclient/cli.py,sha256=4ZedIorMbtVFyqmwlhgXx-_F2w2-at30ef7c7zWcwzM,6781\nnbclient/client.py,sha256=OjAYdEnS_qbOYGPnnLqg7fFHiUcJmotm2NL7MKBBiXE,49833\nnbclient/exceptions.py,sha256=3j6tm0lJVASZHTo4cnpvqBxN9FKEpkHUaYyDG7CrIjY,4065\nnbclient/jsonutil.py,sha256=WPJhDujbq8tC8o1shj4xoganZCBIeIDckL0uOQOfrJY,4612\nnbclient/output_widget.py,sha256=g7EKyKu_jM76OZnQ3nnqpDOdTr0wjQhd7iVJGx-Bo8I,4527\nnbclient/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nnbclient/util.py,sha256=bWzTnKHVBoN9iP1rXYyCGm7qyCQpRQDwDO4FBtjjE7c,544\n | .venv\Lib\site-packages\nbclient-0.10.2.dist-info\RECORD | RECORD | Other | 1,674 | 0.7 | 0 | 0 | node-utils | 229 | 2025-01-01T15:03:03.934119 | GPL-3.0 | false | 15b33246dc331dbb4a89cb30378d76b0 |
Wheel-Version: 1.0\nGenerator: hatchling 1.27.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n | .venv\Lib\site-packages\nbclient-0.10.2.dist-info\WHEEL | WHEEL | Other | 87 | 0.5 | 0 | 0 | vue-tools | 143 | 2024-09-04T14:14:29.868538 | Apache-2.0 | false | e2fcb0ad9ea59332c808928b4b439e7a |
BSD 3-Clause License\n\nCopyright (c) 2020-, Jupyter Development Team\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n | .venv\Lib\site-packages\nbclient-0.10.2.dist-info\licenses\LICENSE | LICENSE | Other | 1,534 | 0.7 | 0 | 0 | awesome-app | 675 | 2024-04-04T02:35:40.118899 | MIT | false | 62f188c37957b44d9adbe64cb1932895 |
"""pytest configuration."""\n\nimport asyncio\nimport os\n\nif os.name == "nt":\n asyncio.set_event_loop_policy(\n asyncio.WindowsSelectorEventLoopPolicy() # type:ignore[attr-defined]\n )\n | .venv\Lib\site-packages\nbconvert\conftest.py | conftest.py | Python | 194 | 0.95 | 0.111111 | 0 | awesome-app | 843 | 2023-07-13T15:30:38.399830 | BSD-3-Clause | true | 7a06d58bd2fc6952b66b50ec7fe352f3 |
#!/usr/bin/env python\n"""NbConvert is a utility for conversion of .ipynb files.\n\nCommand-line interface for the NbConvert conversion utility.\n"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport asyncio\nimport glob\nimport logging\nimport os\nimport sys\nimport typing as t\nfrom textwrap import dedent, fill\n\nfrom jupyter_core.application import JupyterApp, base_aliases, base_flags\nfrom traitlets import Bool, DottedObjectName, Instance, List, Type, Unicode, default, observe\nfrom traitlets.config import Configurable, catch_config_error\nfrom traitlets.utils.importstring import import_item\n\nfrom nbconvert import __version__, exporters, postprocessors, preprocessors, writers\nfrom nbconvert.utils.text import indent\n\nfrom .exporters.base import get_export_names, get_exporter\nfrom .utils.base import NbConvertBase\nfrom .utils.exceptions import ConversionException\nfrom .utils.io import unicode_stdin_stream\n\n# -----------------------------------------------------------------------------\n# Classes and functions\n# -----------------------------------------------------------------------------\n\n\nclass DottedOrNone(DottedObjectName):\n """A string holding a valid dotted object name in Python, such as A.b3._c\n Also allows for None type.\n """\n\n default_value = ""\n\n def validate(self, obj, value):\n """Validate an input."""\n if value is not None and len(value) > 0:\n return super().validate(obj, value)\n return value\n\n\nnbconvert_aliases = {}\nnbconvert_aliases.update(base_aliases)\nnbconvert_aliases.update(\n {\n "to": "NbConvertApp.export_format",\n "template": "TemplateExporter.template_name",\n "template-file": "TemplateExporter.template_file",\n "theme": "HTMLExporter.theme",\n "sanitize_html": "HTMLExporter.sanitize_html",\n "writer": "NbConvertApp.writer_class",\n "post": "NbConvertApp.postprocessor_class",\n "output": "NbConvertApp.output_base",\n "output-dir": "FilesWriter.build_directory",\n "reveal-prefix": "SlidesExporter.reveal_url_prefix",\n "nbformat": "NotebookExporter.nbformat_version",\n }\n)\n\nnbconvert_flags = {}\nnbconvert_flags.update(base_flags)\nnbconvert_flags.update(\n {\n "execute": (\n {"ExecutePreprocessor": {"enabled": True}},\n "Execute the notebook prior to export.",\n ),\n "allow-errors": (\n {"ExecutePreprocessor": {"allow_errors": True}},\n (\n "Continue notebook execution even if one of the cells throws "\n "an error and include the error message in the cell output "\n "(the default behaviour is to abort conversion). This flag "\n "is only relevant if '--execute' was specified, too."\n ),\n ),\n "stdin": (\n {\n "NbConvertApp": {\n "from_stdin": True,\n }\n },\n "read a single notebook file from stdin. Write the resulting notebook with default basename 'notebook.*'",\n ),\n "stdout": (\n {"NbConvertApp": {"writer_class": "StdoutWriter"}},\n "Write notebook output to stdout instead of files.",\n ),\n "inplace": (\n {\n "NbConvertApp": {\n "use_output_suffix": False,\n "export_format": "notebook",\n },\n "FilesWriter": {"build_directory": ""},\n },\n """Run nbconvert in place, overwriting the existing notebook (only\n relevant when converting to notebook format)""",\n ),\n "clear-output": (\n {\n "NbConvertApp": {\n "use_output_suffix": False,\n "export_format": "notebook",\n },\n "FilesWriter": {"build_directory": ""},\n "ClearOutputPreprocessor": {"enabled": True},\n },\n """Clear output of current file and save in place,\n overwriting the existing notebook. """,\n ),\n "coalesce-streams": (\n {\n "NbConvertApp": {"use_output_suffix": False, "export_format": "notebook"},\n "FilesWriter": {"build_directory": ""},\n "CoalesceStreamsPreprocessor": {"enabled": True},\n },\n """Coalesce consecutive stdout and stderr outputs into one stream (within each cell).""",\n ),\n "no-prompt": (\n {\n "TemplateExporter": {\n "exclude_input_prompt": True,\n "exclude_output_prompt": True,\n }\n },\n "Exclude input and output prompts from converted document.",\n ),\n "no-input": (\n {\n "TemplateExporter": {\n "exclude_output_prompt": True,\n "exclude_input": True,\n "exclude_input_prompt": True,\n }\n },\n """Exclude input cells and output prompts from converted document.\n This mode is ideal for generating code-free reports.""",\n ),\n "allow-chromium-download": (\n {\n "WebPDFExporter": {\n "allow_chromium_download": True,\n }\n },\n """Whether to allow downloading chromium if no suitable version is found on the system.""",\n ),\n "disable-chromium-sandbox": (\n {\n "WebPDFExporter": {\n "disable_sandbox": True,\n }\n },\n """Disable chromium security sandbox when converting to PDF..""",\n ),\n "show-input": (\n {\n "TemplateExporter": {\n "exclude_input": False,\n }\n },\n """Shows code input. This flag is only useful for dejavu users.""",\n ),\n "embed-images": (\n {\n "HTMLExporter": {\n "embed_images": True,\n }\n },\n """Embed the images as base64 dataurls in the output. This flag is only useful for the HTML/WebPDF/Slides exports.""",\n ),\n "sanitize-html": (\n {\n "HTMLExporter": {\n "sanitize_html": True,\n }\n },\n """Whether the HTML in Markdown cells and cell outputs should be sanitized..""",\n ),\n }\n)\n\n\nclass NbConvertApp(JupyterApp):\n """Application used to convert from notebook file type (``*.ipynb``)"""\n\n version = __version__\n name = "jupyter-nbconvert"\n aliases = nbconvert_aliases\n flags = nbconvert_flags\n\n @default("log_level")\n def _log_level_default(self):\n return logging.INFO\n\n classes = List() # type:ignore[assignment]\n\n @default("classes")\n def _classes_default(self):\n classes: list[type[t.Any]] = [NbConvertBase]\n for pkg in (exporters, preprocessors, writers, postprocessors):\n for name in dir(pkg):\n cls = getattr(pkg, name)\n if isinstance(cls, type) and issubclass(cls, Configurable):\n classes.append(cls)\n\n return classes\n\n description = Unicode( # type:ignore[assignment]\n """This application is used to convert notebook files (*.ipynb)\n to various other formats.\n\n WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES."""\n )\n\n output_base = Unicode(\n "{notebook_name}",\n help="""Overwrite base name use for output files.\n Supports pattern replacements '{notebook_name}'.\n """,\n ).tag(config=True)\n\n use_output_suffix = Bool(\n True,\n help="""Whether to apply a suffix prior to the extension (only relevant\n when converting to notebook format). The suffix is determined by\n the exporter, and is usually '.nbconvert'.""",\n ).tag(config=True)\n\n output_files_dir = Unicode(\n "{notebook_name}_files",\n help="""Directory to copy extra files (figures) to.\n '{notebook_name}' in the string will be converted to notebook\n basename.""",\n ).tag(config=True)\n\n examples = Unicode(\n f"""\n The simplest way to use nbconvert is\n\n > jupyter nbconvert mynotebook.ipynb --to html\n\n Options include {get_export_names()}.\n\n > jupyter nbconvert --to latex mynotebook.ipynb\n\n Both HTML and LaTeX support multiple output templates. LaTeX includes\n 'base', 'article' and 'report'. HTML includes 'basic', 'lab' and\n 'classic'. You can specify the flavor of the format used.\n\n > jupyter nbconvert --to html --template lab mynotebook.ipynb\n\n You can also pipe the output to stdout, rather than a file\n\n > jupyter nbconvert mynotebook.ipynb --stdout\n\n PDF is generated via latex\n\n > jupyter nbconvert mynotebook.ipynb --to pdf\n\n You can get (and serve) a Reveal.js-powered slideshow\n\n > jupyter nbconvert myslides.ipynb --to slides --post serve\n\n Multiple notebooks can be given at the command line in a couple of\n different ways:\n\n > jupyter nbconvert notebook*.ipynb\n > jupyter nbconvert notebook1.ipynb notebook2.ipynb\n\n or you can specify the notebooks list in a config file, containing::\n\n c.NbConvertApp.notebooks = ["my_notebook.ipynb"]\n\n > jupyter nbconvert --config mycfg.py\n """\n )\n\n # Writer specific variables\n writer = Instance(\n "nbconvert.writers.base.WriterBase",\n help="""Instance of the writer class used to write the\n results of the conversion.""",\n allow_none=True,\n )\n writer_class = DottedObjectName(\n "FilesWriter",\n help="""Writer class used to write the\n results of the conversion""",\n ).tag(config=True)\n writer_aliases = {\n "fileswriter": "nbconvert.writers.files.FilesWriter",\n "debugwriter": "nbconvert.writers.debug.DebugWriter",\n "stdoutwriter": "nbconvert.writers.stdout.StdoutWriter",\n }\n writer_factory = Type(allow_none=True)\n\n @observe("writer_class")\n def _writer_class_changed(self, change):\n new = change["new"]\n if new.lower() in self.writer_aliases:\n new = self.writer_aliases[new.lower()]\n self.writer_factory = import_item(new)\n\n # Post-processor specific variables\n postprocessor = Instance(\n "nbconvert.postprocessors.base.PostProcessorBase",\n help="""Instance of the PostProcessor class used to write the\n results of the conversion.""",\n allow_none=True,\n )\n\n postprocessor_class = DottedOrNone(\n help="""PostProcessor class used to write the\n results of the conversion"""\n ).tag(config=True)\n postprocessor_aliases = {"serve": "nbconvert.postprocessors.serve.ServePostProcessor"}\n postprocessor_factory = Type(None, allow_none=True)\n\n @observe("postprocessor_class")\n def _postprocessor_class_changed(self, change):\n new = change["new"]\n if new.lower() in self.postprocessor_aliases:\n new = self.postprocessor_aliases[new.lower()]\n if new:\n self.postprocessor_factory = import_item(new)\n\n export_format = Unicode( # type:ignore[call-overload]\n allow_none=False,\n help=f"""The export format to be used, either one of the built-in formats\n {get_export_names()}\n or a dotted object name that represents the import path for an\n ``Exporter`` class""",\n ).tag(config=True)\n\n notebooks = List(\n Unicode(),\n help="""List of notebooks to convert.\n Wildcards are supported.\n Filenames passed positionally will be added to the list.\n """,\n ).tag(config=True)\n from_stdin = Bool(False, help="read a single notebook from stdin.").tag(config=True)\n recursive_glob = Bool(\n False, help="set the 'recursive' option for glob for searching wildcards."\n ).tag(config=True)\n\n @catch_config_error\n def initialize(self, argv=None):\n """Initialize application, notebooks, writer, and postprocessor"""\n # See https://bugs.python.org/issue37373 :(\n if sys.version_info > (3, 8) and sys.platform.startswith("win"):\n asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())\n\n self.init_syspath()\n super().initialize(argv)\n if hasattr(self, "load_config_environ"):\n self.load_config_environ()\n self.init_notebooks()\n self.init_writer()\n self.init_postprocessor()\n\n def init_syspath(self):\n """Add the cwd to the sys.path ($PYTHONPATH)"""\n sys.path.insert(0, os.getcwd())\n\n def init_notebooks(self):\n """Construct the list of notebooks.\n\n If notebooks are passed on the command-line,\n they override (rather than add) notebooks specified in config files.\n Glob each notebook to replace notebook patterns with filenames.\n """\n\n # Specifying notebooks on the command-line overrides (rather than\n # adds) the notebook list\n patterns = self.extra_args if self.extra_args else self.notebooks\n\n # Use glob to replace all the notebook patterns with filenames.\n filenames = []\n for pattern in patterns:\n # Use glob to find matching filenames. Allow the user to convert\n # notebooks without having to type the extension.\n globbed_files = glob.glob(pattern, recursive=self.recursive_glob)\n globbed_files.extend(glob.glob(pattern + ".ipynb", recursive=self.recursive_glob))\n if not globbed_files:\n self.log.warning("pattern %r matched no files", pattern)\n\n for filename in globbed_files:\n if filename not in filenames:\n filenames.append(filename)\n self.notebooks = filenames\n\n def init_writer(self):\n """Initialize the writer (which is stateless)"""\n self._writer_class_changed({"new": self.writer_class})\n if self.writer_factory:\n self.writer = self.writer_factory(parent=self)\n if hasattr(self.writer, "build_directory") and self.writer.build_directory != "":\n self.use_output_suffix = False\n\n def init_postprocessor(self):\n """Initialize the postprocessor (which is stateless)"""\n self._postprocessor_class_changed({"new": self.postprocessor_class})\n if self.postprocessor_factory:\n self.postprocessor = self.postprocessor_factory(parent=self)\n\n def start(self):\n """Run start after initialization process has completed"""\n super().start()\n self.convert_notebooks()\n\n def _notebook_filename_to_name(self, notebook_filename):\n """\n Returns the notebook name from the notebook filename by\n applying `output_base` pattern and stripping extension\n """\n basename = os.path.basename(notebook_filename)\n notebook_name = basename[: basename.rfind(".")]\n notebook_name = self.output_base.format(notebook_name=notebook_name)\n\n return notebook_name # noqa: RET504\n\n def init_single_notebook_resources(self, notebook_filename):\n """Step 1: Initialize resources\n\n This initializes the resources dictionary for a single notebook.\n\n Returns\n -------\n dict\n resources dictionary for a single notebook that MUST include the following keys:\n - config_dir: the location of the Jupyter config directory\n - unique_key: the notebook name\n - output_files_dir: a directory where output files (not\n including the notebook itself) should be saved\n """\n notebook_name = self._notebook_filename_to_name(notebook_filename)\n self.log.debug("Notebook name is '%s'", notebook_name)\n\n # first initialize the resources we want to use\n resources = {}\n resources["config_dir"] = self.config_dir\n resources["unique_key"] = notebook_name\n\n output_files_dir = self.output_files_dir.format(notebook_name=notebook_name)\n\n resources["output_files_dir"] = output_files_dir\n\n return resources\n\n def export_single_notebook(self, notebook_filename, resources, input_buffer=None):\n """Step 2: Export the notebook\n\n Exports the notebook to a particular format according to the specified\n exporter. This function returns the output and (possibly modified)\n resources from the exporter.\n\n Parameters\n ----------\n notebook_filename : str\n name of notebook file.\n resources : dict\n input_buffer :\n readable file-like object returning unicode.\n if not None, notebook_filename is ignored\n\n Returns\n -------\n output\n dict\n resources (possibly modified)\n """\n try:\n if input_buffer is not None:\n output, resources = self.exporter.from_file(input_buffer, resources=resources)\n else:\n output, resources = self.exporter.from_filename(\n notebook_filename, resources=resources\n )\n except ConversionException:\n self.log.error("Error while converting '%s'", notebook_filename, exc_info=True) # noqa: G201\n self.exit(1)\n\n return output, resources\n\n def write_single_notebook(self, output, resources):\n """Step 3: Write the notebook to file\n\n This writes output from the exporter to file using the specified writer.\n It returns the results from the writer.\n\n Parameters\n ----------\n output :\n resources : dict\n resources for a single notebook including name, config directory\n and directory to save output\n\n Returns\n -------\n file\n results from the specified writer output of exporter\n """\n\n if "unique_key" not in resources:\n msg = "unique_key MUST be specified in the resources, but it is not"\n raise KeyError(msg)\n\n notebook_name = resources["unique_key"]\n if self.use_output_suffix and self.output_base == "{notebook_name}":\n notebook_name += resources.get("output_suffix", "")\n\n if not self.writer:\n msg = "No writer object defined!"\n raise ValueError(msg)\n return self.writer.write(output, resources, notebook_name=notebook_name)\n\n def postprocess_single_notebook(self, write_results):\n """Step 4: Post-process the written file\n\n Only used if a postprocessor has been specified. After the\n converted notebook is written to a file in Step 3, this post-processes\n the notebook.\n """\n # Post-process if post processor has been defined.\n if hasattr(self, "postprocessor") and self.postprocessor:\n self.postprocessor(write_results)\n\n def convert_single_notebook(self, notebook_filename, input_buffer=None):\n """Convert a single notebook.\n\n Performs the following steps:\n\n 1. Initialize notebook resources\n 2. Export the notebook to a particular format\n 3. Write the exported notebook to file\n 4. (Maybe) postprocess the written file\n\n Parameters\n ----------\n notebook_filename : str\n input_buffer :\n If input_buffer is not None, conversion is done and the buffer is\n used as source into a file basenamed by the notebook_filename\n argument.\n """\n if input_buffer is None:\n self.log.info("Converting notebook %s to %s", notebook_filename, self.export_format)\n else:\n self.log.info("Converting notebook into %s", self.export_format)\n\n resources = self.init_single_notebook_resources(notebook_filename)\n output, resources = self.export_single_notebook(\n notebook_filename, resources, input_buffer=input_buffer\n )\n write_results = self.write_single_notebook(output, resources)\n self.postprocess_single_notebook(write_results)\n\n def convert_notebooks(self):\n """Convert the notebooks in the self.notebooks traitlet"""\n\n # no notebooks to convert!\n if len(self.notebooks) == 0 and not self.from_stdin:\n self.print_help()\n sys.exit(-1)\n\n if not self.export_format:\n msg = (\n "Please specify an output format with '--to <format>'."\n f"\nThe following formats are available: {get_export_names()}"\n )\n raise ValueError(msg)\n\n # initialize the exporter\n cls = get_exporter(self.export_format)\n self.exporter = cls(config=self.config)\n\n # strip duplicate extension from output_base, to avoid Basename.ext.ext\n if getattr(self.exporter, "file_extension", False):\n base, ext = os.path.splitext(self.output_base)\n if ext == self.exporter.file_extension:\n self.output_base = base\n\n # convert each notebook\n if not self.from_stdin:\n for notebook_filename in self.notebooks:\n self.convert_single_notebook(notebook_filename)\n else:\n input_buffer = unicode_stdin_stream()\n # default name when conversion from stdin\n self.convert_single_notebook("notebook.ipynb", input_buffer=input_buffer)\n input_buffer.close()\n\n def document_flag_help(self):\n """\n Return a string containing descriptions of all the flags.\n """\n flags = "The following flags are defined:\n\n"\n for flag, (cfg, fhelp) in self.flags.items():\n flags += f"{flag}\n"\n flags += indent(fill(fhelp, 80)) + "\n\n"\n flags += indent(fill("Long Form: " + str(cfg), 80)) + "\n\n"\n return flags\n\n def document_alias_help(self):\n """Return a string containing all of the aliases"""\n\n aliases = "The following aliases are defined:\n\n"\n for alias, longname in self.aliases.items():\n aliases += f"\t**{alias}** ({longname})\n\n"\n return aliases\n\n def document_config_options(self):\n """\n Provides a much improves version of the configuration documentation by\n breaking the configuration options into app, exporter, writer,\n preprocessor, postprocessor, and other sections.\n """\n categories = {\n category: [c for c in self._classes_inc_parents() if category in c.__name__.lower()]\n for category in ["app", "exporter", "writer", "preprocessor", "postprocessor"]\n }\n accounted_for = {c for category in categories.values() for c in category}\n categories["other"] = [c for c in self._classes_inc_parents() if c not in accounted_for]\n\n header = dedent(\n """\n {section} Options\n -----------------------\n\n """\n )\n sections = ""\n for category in categories:\n sections += header.format(section=category.title())\n if category in ["exporter", "preprocessor", "writer"]:\n sections += f".. image:: _static/{category}_inheritance.png\n\n"\n sections += "\n".join(c.class_config_rst_doc() for c in categories[category])\n\n return sections.replace(" : ", r" \: ")\n\n\nclass DejavuApp(NbConvertApp):\n """A deja vu app."""\n\n def initialize(self, argv=None):\n """Initialize the app."""\n self.config.TemplateExporter.exclude_input = True\n self.config.TemplateExporter.exclude_output_prompt = True\n self.config.TemplateExporter.exclude_input_prompt = True\n self.config.ExecutePreprocessor.enabled = True\n self.config.WebPDFExporter.paginate = False\n self.config.QtPDFExporter.paginate = False\n\n super().initialize(argv)\n if hasattr(self, "load_config_environ"):\n self.load_config_environ()\n\n @default("export_format")\n def _default_export_format(self):\n return "html"\n\n\n# -----------------------------------------------------------------------------\n# Main entry point\n# -----------------------------------------------------------------------------\n\nmain = launch_new_instance = NbConvertApp.launch_instance\ndejavu_main = DejavuApp.launch_instance\n | .venv\Lib\site-packages\nbconvert\nbconvertapp.py | nbconvertapp.py | Python | 24,790 | 0.95 | 0.139912 | 0.042179 | awesome-app | 409 | 2024-12-18T18:58:42.173946 | BSD-3-Clause | false | 4feed92b202ad52f0e0ead280d5df3dc |
"""nbconvert version info."""\n\nimport re\nfrom typing import List\n\n# Version string must appear intact for versioning\n__version__ = "7.16.6"\n\n# Build up version_info tuple for backwards compatibility\npattern = r"(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(?P<rest>.*)"\nmatch = re.match(pattern, __version__)\nassert match is not None\nparts: List[object] = [int(match[part]) for part in ["major", "minor", "patch"]]\nif match["rest"]:\n parts.append(match["rest"])\nversion_info = tuple(parts)\n | .venv\Lib\site-packages\nbconvert\_version.py | _version.py | Python | 492 | 0.95 | 0.25 | 0.153846 | node-utils | 754 | 2025-03-09T12:47:23.338238 | GPL-3.0 | false | 8f15703ecf966d08b37282560712cf9d |
"""Utilities for converting notebooks to and from different formats."""\n\nfrom ._version import __version__, version_info\n\ntry:\n from . import filters, postprocessors, preprocessors, writers\n from .exporters import (\n ASCIIDocExporter,\n Exporter,\n ExporterNameError,\n FilenameExtension,\n HTMLExporter,\n LatexExporter,\n MarkdownExporter,\n NotebookExporter,\n PDFExporter,\n PythonExporter,\n QtPDFExporter,\n QtPNGExporter,\n RSTExporter,\n ScriptExporter,\n SlidesExporter,\n TemplateExporter,\n WebPDFExporter,\n export,\n get_export_names,\n get_exporter,\n )\nexcept ModuleNotFoundError:\n # We hit this condition when the package is not yet fully installed.\n pass\n\n\n__all__ = [\n "__version__",\n "version_info",\n "filters",\n "postprocessors",\n "preprocessors",\n "writers",\n "ASCIIDocExporter",\n "ExporterNameError",\n "export",\n "get_export_names",\n "get_exporter",\n "Exporter",\n "FilenameExtension",\n "HTMLExporter",\n "LatexExporter",\n "MarkdownExporter",\n "NotebookExporter",\n "PDFExporter",\n "PythonExporter",\n "QtPDFExporter",\n "QtPNGExporter",\n "RSTExporter",\n "ScriptExporter",\n "SlidesExporter",\n "TemplateExporter",\n "WebPDFExporter",\n]\n | .venv\Lib\site-packages\nbconvert\__init__.py | __init__.py | Python | 1,364 | 0.95 | 0.032787 | 0.017544 | awesome-app | 586 | 2023-10-14T10:33:29.089524 | MIT | false | dcc6425ccd0c42f035bc7fa184f0f380 |
"""nbconvert cli entry point."""\n\nfrom .nbconvertapp import main\n\nmain()\n | .venv\Lib\site-packages\nbconvert\__main__.py | __main__.py | Python | 73 | 0.65 | 0 | 0 | awesome-app | 968 | 2023-11-20T02:38:32.649188 | Apache-2.0 | false | 34b486e27f0838b2e182567c9b4bf10a |
"""ASCIIDoc Exporter class"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import default\nfrom traitlets.config import Config\n\nfrom .templateexporter import TemplateExporter\n\n\nclass ASCIIDocExporter(TemplateExporter):\n """\n Exports to an ASCIIDoc document (.asciidoc)\n """\n\n @default("file_extension")\n def _file_extension_default(self):\n return ".asciidoc"\n\n @default("template_name")\n def _template_name_default(self):\n return "asciidoc"\n\n output_mimetype = "text/asciidoc"\n export_from_notebook = "AsciiDoc"\n\n @default("raw_mimetypes")\n def _raw_mimetypes_default(self):\n return ["text/asciidoc/", "text/markdown", "text/html", ""]\n\n @property\n def default_config(self):\n c = Config(\n {\n "NbConvertBase": {\n "display_data_priority": [\n "text/html",\n "text/markdown",\n "image/svg+xml",\n "image/png",\n "image/jpeg",\n "text/plain",\n "text/latex",\n ]\n },\n "ExtractOutputPreprocessor": {"enabled": True},\n "HighlightMagicsPreprocessor": {"enabled": True},\n }\n )\n if super().default_config:\n c2 = super().default_config.copy()\n c2.merge(c)\n c = c2\n return c\n | .venv\Lib\site-packages\nbconvert\exporters\asciidoc.py | asciidoc.py | Python | 1,530 | 0.95 | 0.127273 | 0.044444 | python-kit | 432 | 2025-06-06T15:03:06.448338 | BSD-3-Clause | false | 02d3aeddf698ca4f4497c84ec7362100 |
"""Module containing single call export functions."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport os\nimport sys\n\nif sys.version_info < (3, 10):\n from importlib_metadata import entry_points # type:ignore[import-not-found]\nelse:\n from importlib.metadata import entry_points\nfrom nbformat import NotebookNode\nfrom traitlets.config import get_config\nfrom traitlets.log import get_logger\nfrom traitlets.utils.importstring import import_item\n\nfrom .exporter import Exporter\n\n# -----------------------------------------------------------------------------\n# Functions\n# -----------------------------------------------------------------------------\n\n__all__ = [\n "export",\n "Exporter",\n "get_exporter",\n "get_export_names",\n "ExporterNameError",\n]\n\n\nclass ExporterNameError(NameError):\n """An exporter name error."""\n\n\nclass ExporterDisabledError(ValueError):\n """An exporter disabled error."""\n\n\ndef export(exporter, nb, **kw):\n """\n Export a notebook object using specific exporter class.\n\n Parameters\n ----------\n exporter : ``Exporter`` class or instance\n Class or instance of the exporter that should be used. If the\n method initializes its own instance of the class, it is ASSUMED that\n the class type provided exposes a constructor (``__init__``) with the same\n signature as the base Exporter class.\n nb : :class:`~nbformat.NotebookNode`\n The notebook to export.\n config : config (optional, keyword arg)\n User configuration instance.\n resources : dict (optional, keyword arg)\n Resources used in the conversion process.\n\n Returns\n -------\n tuple\n output : str\n The resulting converted notebook.\n resources : dictionary\n Dictionary of resources used prior to and during the conversion\n process.\n """\n\n # Check arguments\n if exporter is None:\n msg = "Exporter is None"\n raise TypeError(msg)\n if not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):\n msg = "exporter does not inherit from Exporter (base)"\n raise TypeError(msg)\n if nb is None:\n msg = "nb is None"\n raise TypeError(msg)\n\n # Create the exporter\n resources = kw.pop("resources", None)\n exporter_instance = exporter if isinstance(exporter, Exporter) else exporter(**kw)\n\n # Try to convert the notebook using the appropriate conversion function.\n if isinstance(nb, NotebookNode):\n output, resources = exporter_instance.from_notebook_node(nb, resources)\n elif isinstance(nb, (str,)):\n output, resources = exporter_instance.from_filename(nb, resources)\n else:\n output, resources = exporter_instance.from_file(nb, resources)\n return output, resources\n\n\ndef get_exporter(name, config=get_config()): # noqa: B008\n """Given an exporter name or import path, return a class ready to be instantiated\n\n Raises ExporterName if exporter is not found or ExporterDisabledError if not enabled\n """\n\n if name == "ipynb":\n name = "notebook"\n\n try:\n exporters = entry_points(group="nbconvert.exporters")\n items = [e for e in exporters if e.name == name or e.name == name.lower()]\n exporter = items[0].load()\n if getattr(exporter(config=config), "enabled", True):\n return exporter\n raise ExporterDisabledError('Exporter "%s" disabled in configuration' % (name))\n except IndexError:\n pass\n\n if "." in name:\n try:\n exporter = import_item(name)\n if getattr(exporter(config=config), "enabled", True):\n return exporter\n raise ExporterDisabledError('Exporter "%s" disabled in configuration' % (name))\n except ImportError:\n log = get_logger()\n log.error("Error importing %s", name, exc_info=True) # noqa: G201\n\n msg = 'Unknown exporter "{}", did you mean one of: {}?'.format(\n name, ", ".join(get_export_names())\n )\n raise ExporterNameError(msg)\n\n\ndef get_export_names(config=get_config()): # noqa: B008\n """Return a list of the currently supported export targets\n\n Exporters can be found in external packages by registering\n them as an nbconvert.exporter entrypoint.\n """\n exporters = sorted(e.name for e in entry_points(group="nbconvert.exporters"))\n if os.environ.get("NBCONVERT_DISABLE_CONFIG_EXPORTERS"):\n get_logger().info(\n "Config exporter loading disabled, no additional exporters will be automatically included."\n )\n return exporters\n\n enabled_exporters = []\n for exporter_name in exporters:\n try:\n e = get_exporter(exporter_name)(config=config)\n if e.enabled:\n enabled_exporters.append(exporter_name)\n except (ExporterDisabledError, ValueError):\n pass\n return enabled_exporters\n | .venv\Lib\site-packages\nbconvert\exporters\base.py | base.py | Python | 4,972 | 0.95 | 0.226667 | 0.065574 | node-utils | 36 | 2024-09-13T20:10:43.512681 | BSD-3-Clause | false | 70d6e2ec9b24918201e12558ce492e14 |
"""This module defines a base Exporter class. For Jinja template-based export,\nsee templateexporter.py.\n"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport collections\nimport copy\nimport datetime\nimport os\nimport sys\nimport typing as t\n\nimport nbformat\nfrom nbformat import NotebookNode, validator\nfrom traitlets import Bool, HasTraits, List, TraitError, Unicode\nfrom traitlets.config import Config\nfrom traitlets.config.configurable import LoggingConfigurable\nfrom traitlets.utils.importstring import import_item\n\n\nclass ResourcesDict(collections.defaultdict): # type:ignore[type-arg]\n """A default dict for resources."""\n\n def __missing__(self, key):\n """Handle missing value."""\n return ""\n\n\nclass FilenameExtension(Unicode): # type:ignore[type-arg]\n """A trait for filename extensions."""\n\n default_value = ""\n info_text = "a filename extension, beginning with a dot"\n\n def validate(self, obj, value):\n """Validate the file name."""\n # cast to proper unicode\n value = super().validate(obj, value)\n\n # check that it starts with a dot\n if value and not value.startswith("."):\n msg = "FileExtension trait '{}' does not begin with a dot: {!r}"\n raise TraitError(msg.format(self.name, value))\n\n return value\n\n\nclass Exporter(LoggingConfigurable):\n """\n Class containing methods that sequentially run a list of preprocessors on a\n NotebookNode object and then return the modified NotebookNode object and\n accompanying resources dict.\n """\n\n enabled = Bool(True, help="Disable this exporter (and any exporters inherited from it).").tag(\n config=True\n )\n\n file_extension = FilenameExtension(\n help="Extension of the file that should be written to disk"\n ).tag(config=True)\n\n optimistic_validation = Bool(\n False,\n help="Reduces the number of validation steps so that it only occurs after all preprocesors have run.",\n ).tag(config=True)\n\n # MIME type of the result file, for HTTP response headers.\n # This is *not* a traitlet, because we want to be able to access it from\n # the class, not just on instances.\n output_mimetype = ""\n\n # Should this converter be accessible from the notebook front-end?\n # If so, should be a friendly name to display (and possibly translated).\n export_from_notebook: str = None # type:ignore[assignment]\n\n # Configurability, allows the user to easily add filters and preprocessors.\n preprocessors: List[t.Any] = List(\n help="""List of preprocessors, by name or namespace, to enable."""\n ).tag(config=True)\n\n _preprocessors: List[t.Any] = List()\n\n default_preprocessors: List[t.Any] = List(\n [\n "nbconvert.preprocessors.TagRemovePreprocessor",\n "nbconvert.preprocessors.RegexRemovePreprocessor",\n "nbconvert.preprocessors.ClearOutputPreprocessor",\n "nbconvert.preprocessors.CoalesceStreamsPreprocessor",\n "nbconvert.preprocessors.ExecutePreprocessor",\n "nbconvert.preprocessors.SVG2PDFPreprocessor",\n "nbconvert.preprocessors.LatexPreprocessor",\n "nbconvert.preprocessors.HighlightMagicsPreprocessor",\n "nbconvert.preprocessors.ExtractOutputPreprocessor",\n "nbconvert.preprocessors.ExtractAttachmentsPreprocessor",\n "nbconvert.preprocessors.ClearMetadataPreprocessor",\n ],\n help="""List of preprocessors available by default, by name, namespace,\n instance, or type.""",\n ).tag(config=True)\n\n def __init__(self, config=None, **kw):\n """\n Public constructor\n\n Parameters\n ----------\n config : ``traitlets.config.Config``\n User configuration instance.\n `**kw`\n Additional keyword arguments passed to parent __init__\n\n """\n with_default_config = self.default_config\n if config:\n with_default_config.merge(config)\n\n super().__init__(config=with_default_config, **kw)\n\n self._init_preprocessors()\n self._nb_metadata = {}\n\n @property\n def default_config(self):\n return Config()\n\n def from_notebook_node(\n self, nb: NotebookNode, resources: t.Any | None = None, **kw: t.Any\n ) -> tuple[NotebookNode, dict[str, t.Any]]:\n """\n Convert a notebook from a notebook node instance.\n\n Parameters\n ----------\n nb : :class:`~nbformat.NotebookNode`\n Notebook node (dict-like with attr-access)\n resources : dict\n Additional resources that can be accessed read/write by\n preprocessors and filters.\n `**kw`\n Ignored\n\n """\n nb_copy = copy.deepcopy(nb)\n resources = self._init_resources(resources)\n\n if "language" in nb["metadata"]:\n resources["language"] = nb["metadata"]["language"].lower()\n\n # Preprocess\n nb_copy, resources = self._preprocess(nb_copy, resources)\n notebook_name = ""\n if resources is not None:\n name = resources.get("metadata", {}).get("name", "")\n path = resources.get("metadata", {}).get("path", "")\n notebook_name = os.path.join(path, name)\n self._nb_metadata[notebook_name] = nb_copy.metadata\n return nb_copy, resources\n\n def from_filename(\n self, filename: str, resources: dict[str, t.Any] | None = None, **kw: t.Any\n ) -> tuple[NotebookNode, dict[str, t.Any]]:\n """\n Convert a notebook from a notebook file.\n\n Parameters\n ----------\n filename : str\n Full filename of the notebook file to open and convert.\n resources : dict\n Additional resources that can be accessed read/write by\n preprocessors and filters.\n `**kw`\n Ignored\n\n """\n # Pull the metadata from the filesystem.\n if resources is None:\n resources = ResourcesDict()\n if "metadata" not in resources or resources["metadata"] == "":\n resources["metadata"] = ResourcesDict()\n path, basename = os.path.split(filename)\n notebook_name = os.path.splitext(basename)[0]\n resources["metadata"]["name"] = notebook_name\n resources["metadata"]["path"] = path\n\n modified_date = datetime.datetime.fromtimestamp(\n os.path.getmtime(filename), tz=datetime.timezone.utc\n )\n # datetime.strftime date format for ipython\n if sys.platform == "win32":\n date_format = "%B %d, %Y"\n else:\n date_format = "%B %-d, %Y"\n resources["metadata"]["modified_date"] = modified_date.strftime(date_format)\n\n with open(filename, encoding="utf-8") as f:\n return self.from_file(f, resources=resources, **kw)\n\n def from_file(\n self, file_stream: t.Any, resources: dict[str, t.Any] | None = None, **kw: t.Any\n ) -> tuple[NotebookNode, dict[str, t.Any]]:\n """\n Convert a notebook from a notebook file.\n\n Parameters\n ----------\n file_stream : file-like object\n Notebook file-like object to convert.\n resources : dict\n Additional resources that can be accessed read/write by\n preprocessors and filters.\n `**kw`\n Ignored\n\n """\n return self.from_notebook_node(\n nbformat.read(file_stream, as_version=4), resources=resources, **kw\n )\n\n def register_preprocessor(self, preprocessor, enabled=False):\n """\n Register a preprocessor.\n Preprocessors are classes that act upon the notebook before it is\n passed into the Jinja templating engine. Preprocessors are also\n capable of passing additional information to the Jinja\n templating engine.\n\n Parameters\n ----------\n preprocessor : `nbconvert.preprocessors.Preprocessor`\n A dotted module name, a type, or an instance\n enabled : bool\n Mark the preprocessor as enabled\n\n """\n if preprocessor is None:\n msg = "preprocessor must not be None"\n raise TypeError(msg)\n isclass = isinstance(preprocessor, type)\n constructed = not isclass\n\n # Handle preprocessor's registration based on it's type\n if constructed and isinstance(\n preprocessor,\n str,\n ):\n # Preprocessor is a string, import the namespace and recursively call\n # this register_preprocessor method\n preprocessor_cls = import_item(preprocessor)\n return self.register_preprocessor(preprocessor_cls, enabled)\n\n if constructed and callable(preprocessor):\n # Preprocessor is a function, no need to construct it.\n # Register and return the preprocessor.\n if enabled:\n preprocessor.enabled = True\n self._preprocessors.append(preprocessor)\n return preprocessor\n\n if isclass and issubclass(preprocessor, HasTraits):\n # Preprocessor is configurable. Make sure to pass in new default for\n # the enabled flag if one was specified.\n self.register_preprocessor(preprocessor(parent=self), enabled)\n return None\n\n if isclass:\n # Preprocessor is not configurable, construct it\n self.register_preprocessor(preprocessor(), enabled)\n return None\n\n # Preprocessor is an instance of something without a __call__\n # attribute.\n raise TypeError(\n "preprocessor must be callable or an importable constructor, got %r" % preprocessor\n )\n\n def _init_preprocessors(self):\n """\n Register all of the preprocessors needed for this exporter, disabled\n unless specified explicitly.\n """\n self._preprocessors = []\n\n # Load default preprocessors (not necessarily enabled by default).\n for preprocessor in self.default_preprocessors:\n self.register_preprocessor(preprocessor)\n\n # Load user-specified preprocessors. Enable by default.\n for preprocessor in self.preprocessors:\n self.register_preprocessor(preprocessor, enabled=True)\n\n def _init_resources(self, resources):\n # Make sure the resources dict is of ResourcesDict type.\n if resources is None:\n resources = ResourcesDict()\n if not isinstance(resources, ResourcesDict):\n new_resources = ResourcesDict()\n new_resources.update(resources)\n resources = new_resources\n\n # Make sure the metadata extension exists in resources\n if "metadata" in resources:\n if not isinstance(resources["metadata"], ResourcesDict):\n new_metadata = ResourcesDict()\n new_metadata.update(resources["metadata"])\n resources["metadata"] = new_metadata\n else:\n resources["metadata"] = ResourcesDict()\n if not resources["metadata"]["name"]:\n resources["metadata"]["name"] = "Notebook"\n\n # Set the output extension\n resources["output_extension"] = self.file_extension\n return resources\n\n def _validate_preprocessor(self, nbc, preprocessor):\n try:\n nbformat.validate(nbc, relax_add_props=True)\n except nbformat.ValidationError:\n self.log.error("Notebook is invalid after preprocessor %s", preprocessor)\n raise\n\n def _preprocess(self, nb, resources):\n """\n Preprocess the notebook before passing it into the Jinja engine.\n To preprocess the notebook is to successively apply all the\n enabled preprocessors. Output from each preprocessor is passed\n along to the next one.\n\n Parameters\n ----------\n nb : notebook node\n notebook that is being exported.\n resources : a dict of additional resources that\n can be accessed read/write by preprocessors\n """\n\n # Do a copy.deepcopy first,\n # we are never safe enough with what the preprocessors could do.\n nbc = copy.deepcopy(nb)\n resc = copy.deepcopy(resources)\n\n if hasattr(validator, "normalize"):\n _, nbc = validator.normalize(nbc)\n\n # Run each preprocessor on the notebook. Carry the output along\n # to each preprocessor\n for preprocessor in self._preprocessors:\n nbc, resc = preprocessor(nbc, resc)\n if not self.optimistic_validation:\n self._validate_preprocessor(nbc, preprocessor)\n\n if self.optimistic_validation:\n self._validate_preprocessor(nbc, preprocessor)\n\n return nbc, resc\n | .venv\Lib\site-packages\nbconvert\exporters\exporter.py | exporter.py | Python | 12,877 | 0.95 | 0.141667 | 0.107744 | react-lib | 191 | 2023-11-28T05:56:38.059407 | Apache-2.0 | false | 3202a05fc1a559b6d66739f18d326112 |
"""HTML Exporter class"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport base64\nimport json\nimport mimetypes\nimport os\nfrom pathlib import Path\nfrom typing import Any, Dict, Optional, Tuple\n\nimport jinja2\nimport markupsafe\nfrom bs4 import BeautifulSoup\nfrom jupyter_core.paths import jupyter_path\nfrom traitlets import Bool, Unicode, default, validate\nfrom traitlets import Dict as TraitletsDict\nfrom traitlets.config import Config\n\nif tuple(int(x) for x in jinja2.__version__.split(".")[:3]) < (3, 0, 0):\n from jinja2 import contextfilter # type:ignore[attr-defined]\nelse:\n from jinja2 import pass_context as contextfilter\n\nfrom jinja2.loaders import split_template_path\nfrom nbformat import NotebookNode\n\nfrom nbconvert.filters.highlight import Highlight2HTML\nfrom nbconvert.filters.markdown_mistune import IPythonRenderer, MarkdownWithMath\nfrom nbconvert.filters.widgetsdatatypefilter import WidgetsDataTypeFilter\nfrom nbconvert.utils.iso639_1 import iso639_1\n\nfrom .templateexporter import TemplateExporter\n\n\ndef find_lab_theme(theme_name):\n """\n Find a JupyterLab theme location by name.\n\n Parameters\n ----------\n theme_name : str\n The name of the labextension theme you want to find.\n\n Raises\n ------\n ValueError\n If the theme was not found, or if it was not specific enough.\n\n Returns\n -------\n theme_name: str\n Full theme name (with scope, if any)\n labextension_path : Path\n The path to the found labextension on the system.\n """\n paths = jupyter_path("labextensions")\n\n matching_themes = []\n theme_path = None\n for path in paths:\n for dirpath, dirnames, filenames in os.walk(path):\n # If it's a federated labextension that contains themes\n if "package.json" in filenames and "themes" in dirnames:\n # TODO Find the theme name in the JS code instead?\n # TODO Find if it's a light or dark theme?\n with open(Path(dirpath) / "package.json", encoding="utf-8") as fobj:\n labext_name = json.loads(fobj.read())["name"]\n\n if labext_name == theme_name or theme_name in labext_name.split("/"):\n matching_themes.append(labext_name)\n\n full_theme_name = labext_name\n theme_path = Path(dirpath) / "themes" / labext_name\n\n if len(matching_themes) == 0:\n msg = f'Could not find lab theme "{theme_name}"'\n raise ValueError(msg)\n\n if len(matching_themes) > 1:\n msg = (\n f'Found multiple themes matching "{theme_name}": {matching_themes}. '\n "Please be more specific about which theme you want to use."\n )\n raise ValueError(msg)\n\n return full_theme_name, theme_path\n\n\nclass HTMLExporter(TemplateExporter):\n """\n Exports a basic HTML document. This exporter assists with the export of\n HTML. Inherit from it if you are writing your own HTML template and need\n custom preprocessors/filters. If you don't need custom preprocessors/\n filters, just change the 'template_file' config option.\n """\n\n export_from_notebook = "HTML"\n\n anchor_link_text = Unicode("¶", help="The text used as the text for anchor links.").tag(\n config=True\n )\n\n exclude_anchor_links = Bool(False, help="If anchor links should be included or not.").tag(\n config=True\n )\n\n require_js_url = Unicode(\n "https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js",\n help="""\n URL to load require.js from.\n\n Defaults to loading from cdnjs.\n """,\n ).tag(config=True)\n\n mathjax_url = Unicode(\n "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS_CHTML-full,Safe",\n help="""\n URL to load Mathjax from.\n\n Defaults to loading from cdnjs.\n """,\n ).tag(config=True)\n\n mermaid_js_url = Unicode(\n "https://cdnjs.cloudflare.com/ajax/libs/mermaid/10.7.0/mermaid.esm.min.mjs",\n help="""\n URL to load MermaidJS from.\n\n Defaults to loading from cdnjs.\n """,\n )\n\n jquery_url = Unicode(\n "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js",\n help="""\n URL to load jQuery from.\n\n Defaults to loading from cdnjs.\n """,\n ).tag(config=True)\n\n jupyter_widgets_base_url = Unicode(\n "https://unpkg.com/", help="URL base for Jupyter widgets"\n ).tag(config=True)\n\n widget_renderer_url = Unicode("", help="Full URL for Jupyter widgets").tag(config=True)\n\n html_manager_semver_range = Unicode(\n "*", help="Semver range for Jupyter widgets HTML manager"\n ).tag(config=True)\n\n @default("file_extension")\n def _file_extension_default(self):\n return ".html"\n\n @default("template_name")\n def _template_name_default(self):\n return "lab"\n\n theme = Unicode(\n "light",\n help="Template specific theme(e.g. the name of a JupyterLab CSS theme distributed as prebuilt extension for the lab template)",\n ).tag(config=True)\n\n sanitize_html = Bool(\n False,\n help=(\n "Whether the HTML in Markdown cells and cell outputs should be sanitized."\n "This should be set to True by nbviewer or similar tools."\n ),\n ).tag(config=True)\n\n skip_svg_encoding = Bool(\n False,\n help=("Whether the svg to image data attribute encoding should occur"),\n ).tag(config=True)\n\n embed_images = Bool(\n False, help="Whether or not to embed images as base64 in markdown cells."\n ).tag(config=True)\n\n output_mimetype = "text/html"\n\n lexer_options = TraitletsDict(\n {},\n help=(\n "Options to be passed to the pygments lexer for highlighting markdown code blocks. "\n "See https://pygments.org/docs/lexers/#available-lexers for available options."\n ),\n ).tag(config=True)\n\n @property\n def default_config(self):\n c = Config(\n {\n "NbConvertBase": {\n "display_data_priority": [\n "application/vnd.jupyter.widget-view+json",\n "application/javascript",\n "text/html",\n "text/markdown",\n "image/svg+xml",\n "text/vnd.mermaid",\n "text/latex",\n "image/png",\n "image/jpeg",\n "text/plain",\n ]\n },\n "HighlightMagicsPreprocessor": {"enabled": True},\n }\n )\n if super().default_config:\n c2 = super().default_config.copy()\n c2.merge(c)\n c = c2\n return c\n\n language_code = Unicode(\n "en", help="Language code of the content, should be one of the ISO639-1"\n ).tag(config=True)\n\n @validate("language_code")\n def _valid_language_code(self, proposal):\n if self.language_code not in iso639_1:\n self.log.warning(\n '"%s" is not an ISO 639-1 language code. '\n 'It has been replaced by the default value "en".',\n self.language_code,\n )\n return proposal["trait"].default_value\n return proposal["value"]\n\n @contextfilter\n def markdown2html(self, context, source):\n """Markdown to HTML filter respecting the anchor_link_text setting"""\n cell = context.get("cell", {})\n attachments = cell.get("attachments", {})\n path = context.get("resources", {}).get("metadata", {}).get("path", "")\n\n renderer = IPythonRenderer(\n escape=False,\n attachments=attachments,\n embed_images=self.embed_images,\n path=path,\n anchor_link_text=self.anchor_link_text,\n exclude_anchor_links=self.exclude_anchor_links,\n **self.lexer_options,\n )\n return MarkdownWithMath(renderer=renderer).render(source)\n\n def default_filters(self):\n """Get the default filters."""\n yield from super().default_filters()\n yield ("markdown2html", self.markdown2html)\n\n def from_notebook_node( # type:ignore[explicit-override, override]\n self, nb: NotebookNode, resources: Optional[Dict[str, Any]] = None, **kw: Any\n ) -> Tuple[str, Dict[str, Any]]:\n """Convert from notebook node."""\n langinfo = nb.metadata.get("language_info", {})\n lexer = langinfo.get("pygments_lexer", langinfo.get("name", None))\n highlight_code = self.filters.get(\n "highlight_code", Highlight2HTML(pygments_lexer=lexer, parent=self)\n )\n\n resources = self._init_resources(resources)\n\n filter_data_type = WidgetsDataTypeFilter(\n notebook_metadata=self._nb_metadata, parent=self, resources=resources\n )\n\n self.register_filter("highlight_code", highlight_code)\n self.register_filter("filter_data_type", filter_data_type)\n html, resources = super().from_notebook_node(nb, resources, **kw)\n soup = BeautifulSoup(html, features="html.parser")\n # Add image's alternative text\n missing_alt = 0\n for elem in soup.select("img:not([alt])"):\n elem.attrs["alt"] = "No description has been provided for this image"\n missing_alt += 1\n if missing_alt:\n self.log.warning("Alternative text is missing on %s image(s).", missing_alt)\n # Set input and output focusable\n for elem in soup.select(".jp-Notebook div.jp-Cell-inputWrapper"):\n elem.attrs["tabindex"] = "0"\n for elem in soup.select(".jp-Notebook div.jp-OutputArea-output"):\n elem.attrs["tabindex"] = "0"\n\n return str(soup), resources\n\n def _init_resources(self, resources):\n def resources_include_css(name):\n env = self.environment\n code = """<style type="text/css">\n%s</style>""" % (env.loader.get_source(env, name)[0])\n return markupsafe.Markup(code)\n\n def resources_include_lab_theme(name):\n # Try to find the theme with the given name, looking through the labextensions\n _, theme_path = find_lab_theme(name)\n\n with open(theme_path / "index.css") as file:\n data = file.read()\n\n # Embed assets (fonts, images...)\n for asset in os.listdir(theme_path):\n local_url = f"url({Path(asset).as_posix()})"\n\n if local_url in data:\n mime_type = mimetypes.guess_type(asset)[0]\n\n # Replace asset url by a base64 dataurl\n with open(theme_path / asset, "rb") as assetfile:\n base64_data = base64.b64encode(assetfile.read())\n base64_str = base64_data.replace(b"\n", b"").decode("ascii")\n\n data = data.replace(local_url, f"url(data:{mime_type};base64,{base64_str})")\n\n code = """<style type="text/css">\n%s</style>""" % data\n return markupsafe.Markup(code)\n\n def resources_include_js(name, module=False):\n """Get the resources include JS for a name. If module=True, import as ES module"""\n env = self.environment\n code = f"""<script {'type="module"' if module else ""}>\n{env.loader.get_source(env, name)[0]}</script>"""\n return markupsafe.Markup(code)\n\n def resources_include_url(name):\n """Get the resources include url for a name."""\n env = self.environment\n mime_type, encoding = mimetypes.guess_type(name)\n try:\n # we try to load via the jinja loader, but that tries to load\n # as (encoded) text\n data = env.loader.get_source(env, name)[0].encode("utf8")\n except UnicodeDecodeError:\n # if that fails (for instance a binary file, png or ttf)\n # we mimic jinja2\n pieces = split_template_path(name)\n for searchpath in self.template_paths:\n filename = os.path.join(searchpath, *pieces)\n if os.path.exists(filename):\n with open(filename, "rb") as f:\n data = f.read()\n break\n else:\n msg = f"No file {name!r} found in {searchpath!r}"\n raise ValueError(msg)\n data = base64.b64encode(data)\n data = data.replace(b"\n", b"").decode("ascii")\n src = f"data:{mime_type};base64,{data}"\n return markupsafe.Markup(src)\n\n resources = super()._init_resources(resources)\n resources["theme"] = self.theme\n resources["include_css"] = resources_include_css\n resources["include_lab_theme"] = resources_include_lab_theme\n resources["include_js"] = resources_include_js\n resources["include_url"] = resources_include_url\n resources["require_js_url"] = self.require_js_url\n resources["mathjax_url"] = self.mathjax_url\n resources["mermaid_js_url"] = self.mermaid_js_url\n resources["jquery_url"] = self.jquery_url\n resources["jupyter_widgets_base_url"] = self.jupyter_widgets_base_url\n resources["widget_renderer_url"] = self.widget_renderer_url\n resources["html_manager_semver_range"] = self.html_manager_semver_range\n resources["should_sanitize_html"] = self.sanitize_html\n resources["language_code"] = self.language_code\n resources["should_not_encode_svg"] = self.skip_svg_encoding\n return resources\n | .venv\Lib\site-packages\nbconvert\exporters\html.py | html.py | Python | 13,779 | 0.95 | 0.13941 | 0.048544 | awesome-app | 351 | 2023-08-29T21:28:37.567664 | BSD-3-Clause | false | a705402094eaeabfad39a4ff0ea0adc0 |
"""LaTeX Exporter class"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport os\n\nfrom traitlets import default\nfrom traitlets.config import Config\n\nfrom nbconvert.filters.filter_links import resolve_references\nfrom nbconvert.filters.highlight import Highlight2Latex\nfrom nbconvert.filters.pandoc import ConvertExplicitlyRelativePaths\n\nfrom .templateexporter import TemplateExporter\n\n\nclass LatexExporter(TemplateExporter):\n """\n Exports to a Latex template. Inherit from this class if your template is\n LaTeX based and you need custom transformers/filters.\n If you don't need custom transformers/filters, just change the\n 'template_file' config option. Place your template in the special "/latex"\n subfolder of the "../templates" folder.\n """\n\n export_from_notebook = "LaTeX"\n\n @default("file_extension")\n def _file_extension_default(self):\n return ".tex"\n\n @default("template_name")\n def _template_name_default(self):\n return "latex"\n\n output_mimetype = "text/latex"\n\n def default_filters(self):\n """Get the default filters."""\n yield from super().default_filters()\n yield ("resolve_references", resolve_references)\n\n @property\n def default_config(self):\n c = Config(\n {\n "NbConvertBase": {\n "display_data_priority": [\n "text/latex",\n "application/pdf",\n "image/png",\n "image/jpeg",\n "image/svg+xml",\n "text/markdown",\n "text/plain",\n ]\n },\n "ExtractAttachmentsPreprocessor": {"enabled": True},\n "ExtractOutputPreprocessor": {"enabled": True},\n "SVG2PDFPreprocessor": {"enabled": True},\n "LatexPreprocessor": {"enabled": True},\n "SphinxPreprocessor": {"enabled": True},\n "HighlightMagicsPreprocessor": {"enabled": True},\n }\n )\n if super().default_config:\n c2 = super().default_config.copy()\n c2.merge(c)\n c = c2\n return c\n\n def from_notebook_node(self, nb, resources=None, **kw):\n """Convert from notebook node."""\n langinfo = nb.metadata.get("language_info", {})\n lexer = langinfo.get("pygments_lexer", langinfo.get("name", None))\n highlight_code = self.filters.get(\n "highlight_code", Highlight2Latex(pygments_lexer=lexer, parent=self)\n )\n self.register_filter("highlight_code", highlight_code)\n\n # Need to make sure explicit relative paths are visible to latex for pdf conversion\n # https://github.com/jupyter/nbconvert/issues/1998\n nb_path = resources.get("metadata", {}).get("path") if resources else None\n texinputs = os.path.abspath(nb_path) if nb_path else os.getcwd()\n convert_explicitly_relative_paths = self.filters.get(\n "convert_explicitly_relative_paths",\n ConvertExplicitlyRelativePaths(texinputs=texinputs, parent=self),\n )\n self.register_filter("convert_explicitly_relative_paths", convert_explicitly_relative_paths)\n\n return super().from_notebook_node(nb, resources, **kw)\n\n def _create_environment(self):\n environment = super()._create_environment()\n\n # Set special Jinja2 syntax that will not conflict with latex.\n environment.block_start_string = "((*"\n environment.block_end_string = "*))"\n environment.variable_start_string = "((("\n environment.variable_end_string = ")))"\n environment.comment_start_string = "((="\n environment.comment_end_string = "=))"\n\n return environment\n | .venv\Lib\site-packages\nbconvert\exporters\latex.py | latex.py | Python | 3,847 | 0.95 | 0.133333 | 0.05814 | node-utils | 934 | 2025-07-08T00:30:01.077053 | GPL-3.0 | false | f7696eee055adb4328ea88e85858a03b |
"""Markdown Exporter class"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import default\nfrom traitlets.config import Config\n\nfrom .templateexporter import TemplateExporter\n\n\nclass MarkdownExporter(TemplateExporter):\n """\n Exports to a markdown document (.md)\n """\n\n export_from_notebook = "Markdown"\n\n @default("file_extension")\n def _file_extension_default(self):\n return ".md"\n\n @default("template_name")\n def _template_name_default(self):\n return "markdown"\n\n output_mimetype = "text/markdown"\n\n @default("raw_mimetypes")\n def _raw_mimetypes_default(self):\n return ["text/markdown", "text/html", ""]\n\n @property\n def default_config(self):\n c = Config(\n {\n "ExtractAttachmentsPreprocessor": {"enabled": True},\n "ExtractOutputPreprocessor": {"enabled": True},\n "NbConvertBase": {\n "display_data_priority": [\n "text/html",\n "text/markdown",\n "image/svg+xml",\n "text/latex",\n "image/png",\n "image/jpeg",\n "text/plain",\n ]\n },\n "HighlightMagicsPreprocessor": {"enabled": True},\n }\n )\n if super().default_config:\n c2 = super().default_config.copy()\n c2.merge(c)\n c = c2\n return c\n | .venv\Lib\site-packages\nbconvert\exporters\markdown.py | markdown.py | Python | 1,569 | 0.95 | 0.122807 | 0.043478 | awesome-app | 93 | 2025-03-19T04:46:12.725788 | BSD-3-Clause | false | 499d19659dc4148e6384dd52237b9a76 |
"""NotebookExporter class"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport nbformat\nfrom traitlets import Enum, default\n\nfrom .exporter import Exporter\n\n\nclass NotebookExporter(Exporter):\n """Exports to an IPython notebook.\n\n This is useful when you want to use nbconvert's preprocessors to operate on\n a notebook (e.g. to execute it) and then write it back to a notebook file.\n """\n\n nbformat_version = Enum(\n list(nbformat.versions),\n default_value=nbformat.current_nbformat,\n help="""The nbformat version to write.\n Use this to downgrade notebooks.\n """,\n ).tag(config=True)\n\n @default("file_extension")\n def _file_extension_default(self):\n return ".ipynb"\n\n output_mimetype = "application/json"\n export_from_notebook = "Notebook"\n\n def from_notebook_node(self, nb, resources=None, **kw):\n """Convert from notebook node."""\n nb_copy, resources = super().from_notebook_node(nb, resources, **kw)\n if self.nbformat_version != nb_copy.nbformat:\n resources["output_suffix"] = ".v%i" % self.nbformat_version\n else:\n resources["output_suffix"] = ".nbconvert"\n output = nbformat.writes(nb_copy, version=self.nbformat_version)\n if not output.endswith("\n"):\n output = output + "\n"\n return output, resources\n | .venv\Lib\site-packages\nbconvert\exporters\notebook.py | notebook.py | Python | 1,423 | 0.95 | 0.136364 | 0.058824 | python-kit | 198 | 2024-02-13T01:53:05.643968 | GPL-3.0 | false | da57aa6d88fa93828051a658ce76c9c4 |
"""Export to PDF via latex"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport os\nimport shutil\nimport subprocess\nimport sys\nfrom tempfile import TemporaryDirectory\n\nfrom traitlets import Bool, Instance, Integer, List, Unicode, default\n\nfrom nbconvert.utils import _contextlib_chdir\n\nfrom .latex import LatexExporter\n\n\nclass LatexFailed(IOError):\n """Exception for failed latex run\n\n Captured latex output is in error.output.\n """\n\n def __init__(self, output):\n """Initialize the error."""\n self.output = output\n\n def __unicode__(self):\n """Unicode representation."""\n return "PDF creating failed, captured latex output:\n%s" % self.output\n\n def __str__(self):\n """String representation."""\n return self.__unicode__()\n\n\ndef prepend_to_env_search_path(varname, value, envdict):\n """Add value to the environment variable varname in envdict\n\n e.g. prepend_to_env_search_path('BIBINPUTS', '/home/sally/foo', os.environ)\n """\n if not value:\n return # Nothing to add\n\n envdict[varname] = value + os.pathsep + envdict.get(varname, "")\n\n\nclass PDFExporter(LatexExporter):\n """Writer designed to write to PDF files.\n\n This inherits from `LatexExporter`. It creates a LaTeX file in\n a temporary directory using the template machinery, and then runs LaTeX\n to create a pdf.\n """\n\n export_from_notebook = "PDF via LaTeX"\n\n latex_count = Integer(3, help="How many times latex will be called.").tag(config=True)\n\n latex_command = List(\n ["xelatex", "{filename}", "-quiet"], help="Shell command used to compile latex."\n ).tag(config=True)\n\n bib_command = List(["bibtex", "{filename}"], help="Shell command used to run bibtex.").tag(\n config=True\n )\n\n verbose = Bool(False, help="Whether to display the output of latex commands.").tag(config=True)\n\n texinputs = Unicode(help="texinputs dir. A notebook's directory is added")\n writer = Instance("nbconvert.writers.FilesWriter", args=(), kw={"build_directory": "."})\n\n output_mimetype = "application/pdf"\n\n _captured_output = List(Unicode())\n\n @default("file_extension")\n def _file_extension_default(self):\n return ".pdf"\n\n @default("template_extension")\n def _template_extension_default(self):\n return ".tex.j2"\n\n def run_command(self, command_list, filename, count, log_function, raise_on_failure=None):\n """Run command_list count times.\n\n Parameters\n ----------\n command_list : list\n A list of args to provide to Popen. Each element of this\n list will be interpolated with the filename to convert.\n filename : unicode\n The name of the file to convert.\n count : int\n How many times to run the command.\n raise_on_failure: Exception class (default None)\n If provided, will raise the given exception for if an instead of\n returning False on command failure.\n\n Returns\n -------\n success : bool\n A boolean indicating if the command was successful (True)\n or failed (False).\n """\n command = [c.format(filename=filename) for c in command_list]\n\n # This will throw a clearer error if the command is not found\n cmd = shutil.which(command_list[0])\n if cmd is None:\n link = "https://nbconvert.readthedocs.io/en/latest/install.html#installing-tex"\n msg = (\n f"{command_list[0]} not found on PATH, if you have not installed "\n f"{command_list[0]} you may need to do so. Find further instructions "\n f"at {link}."\n )\n raise OSError(msg)\n\n times = "time" if count == 1 else "times"\n self.log.info("Running %s %i %s: %s", command_list[0], count, times, command)\n\n shell = sys.platform == "win32"\n if shell:\n command = subprocess.list2cmdline(command) # type:ignore[assignment]\n env = os.environ.copy()\n prepend_to_env_search_path("TEXINPUTS", self.texinputs, env)\n prepend_to_env_search_path("BIBINPUTS", self.texinputs, env)\n prepend_to_env_search_path("BSTINPUTS", self.texinputs, env)\n\n with open(os.devnull, "rb") as null:\n stdout = subprocess.PIPE if not self.verbose else None\n for _ in range(count):\n p = subprocess.Popen(\n command,\n stdout=stdout,\n stderr=subprocess.STDOUT,\n stdin=null,\n shell=shell, # noqa: S603\n env=env,\n )\n out, _ = p.communicate()\n if p.returncode:\n if self.verbose: # noqa: SIM108\n # verbose means I didn't capture stdout with PIPE,\n # so it's already been displayed and `out` is None.\n out_str = ""\n else:\n out_str = out.decode("utf-8", "replace")\n log_function(command, out)\n self._captured_output.append(out_str)\n if raise_on_failure:\n msg = f'Failed to run "{command}" command:\n{out_str}'\n raise raise_on_failure(msg)\n return False # failure\n return True # success\n\n def run_latex(self, filename, raise_on_failure=LatexFailed):\n """Run xelatex self.latex_count times."""\n\n def log_error(command, out):\n self.log.critical("%s failed: %s\n%s", command[0], command, out)\n\n return self.run_command(\n self.latex_command, filename, self.latex_count, log_error, raise_on_failure\n )\n\n def run_bib(self, filename, raise_on_failure=False):\n """Run bibtex one time."""\n filename = os.path.splitext(filename)[0]\n\n def log_error(command, out):\n self.log.warning(\n "%s had problems, most likely because there were no citations", command[0]\n )\n self.log.debug("%s output: %s\n%s", command[0], command, out)\n\n return self.run_command(self.bib_command, filename, 1, log_error, raise_on_failure)\n\n def from_notebook_node(self, nb, resources=None, **kw):\n """Convert from notebook node."""\n latex, resources = super().from_notebook_node(nb, resources=resources, **kw)\n # set texinputs directory, so that local files will be found\n if resources and resources.get("metadata", {}).get("path"):\n self.texinputs = os.path.abspath(resources["metadata"]["path"])\n else:\n self.texinputs = os.getcwd()\n\n self._captured_outputs = []\n with TemporaryDirectory() as td, _contextlib_chdir.chdir(td):\n notebook_name = "notebook"\n resources["output_extension"] = ".tex"\n tex_file = self.writer.write(latex, resources, notebook_name=notebook_name)\n self.log.info("Building PDF")\n self.run_latex(tex_file)\n if self.run_bib(tex_file):\n self.run_latex(tex_file)\n\n pdf_file = notebook_name + ".pdf"\n if not os.path.isfile(pdf_file):\n raise LatexFailed("\n".join(self._captured_output))\n self.log.info("PDF successfully created")\n with open(pdf_file, "rb") as f:\n pdf_data = f.read()\n\n # convert output extension to pdf\n # the writer above required it to be tex\n resources["output_extension"] = ".pdf"\n # clear figure outputs and attachments, extracted by latex export,\n # so we don't claim to be a multi-file export.\n resources.pop("outputs", None)\n resources.pop("attachments", None)\n\n return pdf_data, resources\n | .venv\Lib\site-packages\nbconvert\exporters\pdf.py | pdf.py | Python | 7,932 | 0.95 | 0.157407 | 0.058824 | vue-tools | 487 | 2024-02-13T21:14:06.491234 | MIT | false | fb3855fefefb213fcbb0e146c71d0ee9 |
"""Python script Exporter class"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import default\n\nfrom .templateexporter import TemplateExporter\n\n\nclass PythonExporter(TemplateExporter):\n """\n Exports a Python code file.\n Note that the file produced will have a shebang of '#!/usr/bin/env python'\n regardless of the actual python version used in the notebook.\n """\n\n @default("file_extension")\n def _file_extension_default(self):\n return ".py"\n\n @default("template_name")\n def _template_name_default(self):\n return "python"\n\n output_mimetype = "text/x-python"\n | .venv\Lib\site-packages\nbconvert\exporters\python.py | python.py | Python | 675 | 0.95 | 0.153846 | 0.111111 | awesome-app | 747 | 2024-07-19T22:27:48.289175 | MIT | false | f0067bc3d18fe0e7bd7dff3847af9d9d |
"""Export to PDF via a headless browser"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import Bool\n\nfrom .qt_exporter import QtExporter\n\n\nclass QtPDFExporter(QtExporter):\n """Writer designed to write to PDF files.\n\n This inherits from :class:`HTMLExporter`. It creates the HTML using the\n template machinery, and then uses pyqtwebengine to create a pdf.\n """\n\n export_from_notebook = "PDF via HTML"\n format = "pdf"\n\n paginate = Bool( # type:ignore[assignment]\n True,\n help="""\n Split generated notebook into multiple pages.\n\n If False, a PDF with one long page will be generated.\n\n Set to True to match behavior of LaTeX based PDF generator\n """,\n ).tag(config=True)\n | .venv\Lib\site-packages\nbconvert\exporters\qtpdf.py | qtpdf.py | Python | 808 | 0.95 | 0.066667 | 0.1 | python-kit | 182 | 2023-10-12T16:15:08.110754 | MIT | false | 4710c895b49131cd936c18d9e02512c5 |
"""Export to PNG via a headless browser"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom .qt_exporter import QtExporter\n\n\nclass QtPNGExporter(QtExporter):\n """Writer designed to write to PNG files.\n\n This inherits from :class:`HTMLExporter`. It creates the HTML using the\n template machinery, and then uses pyqtwebengine to create a png.\n """\n\n export_from_notebook = "PNG via HTML"\n format = "png"\n | .venv\Lib\site-packages\nbconvert\exporters\qtpng.py | qtpng.py | Python | 479 | 0.95 | 0.117647 | 0.181818 | node-utils | 823 | 2024-05-04T16:47:03.533761 | BSD-3-Clause | false | acecace2a35070ae8218558924c85549 |
"""A qt exporter."""\n\nimport os\nimport sys\nimport tempfile\n\nfrom traitlets import default\n\nfrom .html import HTMLExporter\n\n\nclass QtExporter(HTMLExporter):\n """A qt exporter."""\n\n paginate = None\n format = ""\n\n @default("file_extension")\n def _file_extension_default(self):\n return ".html"\n\n def _check_launch_reqs(self):\n if sys.platform.startswith("win") and self.format == "png":\n msg = "Exporting to PNG using Qt is currently not supported on Windows."\n raise RuntimeError(msg)\n from .qt_screenshot import QT_INSTALLED\n\n if not QT_INSTALLED:\n msg = (\n f"PyQtWebEngine is not installed to support Qt {self.format.upper()} conversion. "\n f"Please install `nbconvert[qt{self.format}]` to enable."\n )\n raise RuntimeError(msg)\n from .qt_screenshot import QtScreenshot\n\n return QtScreenshot\n\n def _run_pyqtwebengine(self, html):\n ext = ".html"\n temp_file = tempfile.NamedTemporaryFile(suffix=ext, delete=False)\n filename = f"{temp_file.name[:-len(ext)]}.{self.format}"\n with temp_file:\n temp_file.write(html.encode("utf-8"))\n try:\n QtScreenshot = self._check_launch_reqs()\n s = QtScreenshot()\n s.capture(f"file://{temp_file.name}", filename, self.paginate)\n finally:\n # Ensure the file is deleted even if pyqtwebengine raises an exception\n os.unlink(temp_file.name)\n return s.data\n\n def from_notebook_node(self, nb, resources=None, **kw):\n """Convert from notebook node."""\n self._check_launch_reqs()\n html, resources = super().from_notebook_node(nb, resources=resources, **kw)\n\n self.log.info("Building %s", self.format.upper())\n data = self._run_pyqtwebengine(html)\n self.log.info("%s successfully created", self.format.upper())\n\n # convert output extension\n # the writer above required it to be html\n resources["output_extension"] = f".{self.format}"\n\n return data, resources\n | .venv\Lib\site-packages\nbconvert\exporters\qt_exporter.py | qt_exporter.py | Python | 2,113 | 0.95 | 0.136364 | 0.058824 | node-utils | 733 | 2025-06-17T16:33:27.275546 | Apache-2.0 | false | 44bd1c496fe7baff7649d208fa327d95 |
"""A qt screenshot exporter."""\n\nimport os\n\ntry:\n from PyQt5 import QtCore # type:ignore[import-not-found]\n from PyQt5.QtGui import QPageLayout, QPageSize # type:ignore[import-not-found]\n from PyQt5.QtWebEngineWidgets import ( # type:ignore[import-not-found]\n QWebEngineSettings,\n QWebEngineView,\n )\n from PyQt5.QtWidgets import QApplication # type:ignore[import-not-found]\n\n QT_INSTALLED = True\nexcept ModuleNotFoundError:\n QT_INSTALLED = False\n\n\nif QT_INSTALLED:\n APP = None\n if not QApplication.instance():\n APP = QApplication([])\n\n class QtScreenshot(QWebEngineView): # type:ignore[misc]\n """A qt screenshot exporter."""\n\n def __init__(self):\n """Initialize the exporter."""\n super().__init__()\n self.app = APP\n\n def capture(self, url, output_file, paginate):\n """Capture the screenshot."""\n self.output_file = output_file\n self.paginate = paginate\n self.load(QtCore.QUrl(url))\n self.loadFinished.connect(self.on_loaded)\n # Create hidden view without scrollbars\n self.setAttribute(QtCore.Qt.WA_DontShowOnScreen)\n self.page().settings().setAttribute(QWebEngineSettings.ShowScrollBars, False)\n self.data = b""\n if output_file.endswith(".pdf"):\n self.export = self.export_pdf\n\n def cleanup(*args):\n """Cleanup the app."""\n self.app.quit() # type:ignore[union-attr]\n self.get_data()\n\n self.page().pdfPrintingFinished.connect(cleanup)\n elif output_file.endswith(".png"):\n self.export = self.export_png\n else:\n msg = f"Export file extension not supported: {output_file}"\n raise RuntimeError(msg)\n self.show()\n self.app.exec() # type:ignore[union-attr]\n\n def on_loaded(self):\n """Handle app load."""\n self.size = self.page().contentsSize().toSize()\n self.resize(self.size)\n # Wait for resize\n QtCore.QTimer.singleShot(1000, self.export)\n\n def export_pdf(self):\n """Export to pdf."""\n if self.paginate:\n page_size = QPageSize(QPageSize.A4)\n page_layout = QPageLayout(page_size, QPageLayout.Portrait, QtCore.QMarginsF())\n else:\n factor = 0.75\n page_size = QPageSize(\n QtCore.QSizeF(self.size.width() * factor, self.size.height() * factor),\n QPageSize.Point,\n )\n page_layout = QPageLayout(page_size, QPageLayout.Portrait, QtCore.QMarginsF())\n\n self.page().printToPdf(self.output_file, pageLayout=page_layout)\n\n def export_png(self):\n """Export to png."""\n self.grab().save(self.output_file, "PNG")\n self.app.quit() # type:ignore[union-attr]\n self.get_data()\n\n def get_data(self):\n """Get output data."""\n if os.path.exists(self.output_file):\n with open(self.output_file, "rb") as f:\n self.data = f.read()\n os.unlink(self.output_file)\n | .venv\Lib\site-packages\nbconvert\exporters\qt_screenshot.py | qt_screenshot.py | Python | 3,312 | 0.95 | 0.163043 | 0.025974 | node-utils | 242 | 2024-10-18T14:29:05.867653 | GPL-3.0 | false | f36aa653ecda6d36f96a9baf5be1f6d4 |
"""reStructuredText Exporter class"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import default\nfrom traitlets.config import Config\n\nfrom ..filters import DataTypeFilter\nfrom .templateexporter import TemplateExporter\n\n\nclass RSTExporter(TemplateExporter):\n """\n Exports reStructuredText documents.\n """\n\n @default("file_extension")\n def _file_extension_default(self):\n return ".rst"\n\n @default("template_name")\n def _template_name_default(self):\n return "rst"\n\n @default("raw_mimetypes")\n def _raw_mimetypes_default(self):\n # Up to summer 2024, nbconvert had a mistaken output_mimetype.\n # Listing that as an extra option here maintains compatibility for\n # notebooks with raw cells marked as that mimetype.\n return [self.output_mimetype, "text/restructuredtext", ""]\n\n output_mimetype = "text/x-rst"\n export_from_notebook = "reST"\n\n def default_filters(self):\n """Override filter_data_type to use native rst outputs"""\n dtf = DataTypeFilter()\n dtf.display_data_priority = [self.output_mimetype, *dtf.display_data_priority]\n filters = dict(super().default_filters())\n filters["filter_data_type"] = dtf\n return filters.items()\n\n @property\n def default_config(self):\n c = Config(\n {\n "CoalesceStreamsPreprocessor": {"enabled": True},\n "ExtractOutputPreprocessor": {"enabled": True},\n "HighlightMagicsPreprocessor": {"enabled": True},\n }\n )\n if super().default_config:\n c2 = super().default_config.copy()\n c2.merge(c)\n c = c2\n return c\n | .venv\Lib\site-packages\nbconvert\exporters\rst.py | rst.py | Python | 1,762 | 0.95 | 0.157895 | 0.108696 | python-kit | 833 | 2023-10-15T19:49:49.473204 | BSD-3-Clause | false | b028e8d97ff1045146b78bb9d891c08d |
"""Generic script exporter class for any kernel language"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport sys\n\nif sys.version_info < (3, 10):\n from importlib_metadata import entry_points # type:ignore[import-not-found]\nelse:\n from importlib.metadata import entry_points\nfrom traitlets import Dict, default\n\nfrom .base import get_exporter\nfrom .templateexporter import TemplateExporter\n\n\nclass ScriptExporter(TemplateExporter):\n """A script exporter."""\n\n # Caches of already looked-up and instantiated exporters for delegation:\n _exporters = Dict()\n _lang_exporters = Dict()\n export_from_notebook = "Script"\n\n @default("template_file")\n def _template_file_default(self):\n return "script.j2"\n\n @default("template_name")\n def _template_name_default(self):\n return "script"\n\n def _get_language_exporter(self, lang_name):\n """Find an exporter for the language name from notebook metadata.\n\n Uses the nbconvert.exporters.script group of entry points.\n Returns None if no exporter is found.\n """\n if lang_name not in self._lang_exporters:\n try:\n exporters = entry_points(group="nbconvert.exporters.script")\n exporter = [e for e in exporters if e.name == lang_name][0].load() # noqa: RUF015\n except (KeyError, IndexError):\n self._lang_exporters[lang_name] = None\n else:\n # TODO: passing config is wrong, but changing this revealed more complicated issues\n self._lang_exporters[lang_name] = exporter(config=self.config, parent=self)\n return self._lang_exporters[lang_name]\n\n def from_notebook_node(self, nb, resources=None, **kw):\n """Convert from notebook node."""\n langinfo = nb.metadata.get("language_info", {})\n\n # delegate to custom exporter, if specified\n exporter_name = langinfo.get("nbconvert_exporter")\n if exporter_name and exporter_name != "script":\n self.log.debug("Loading script exporter: %s", exporter_name)\n if exporter_name not in self._exporters:\n exporter = get_exporter(exporter_name)\n # TODO: passing config is wrong, but changing this revealed more complicated issues\n self._exporters[exporter_name] = exporter(config=self.config, parent=self)\n exporter = self._exporters[exporter_name]\n return exporter.from_notebook_node(nb, resources, **kw)\n\n # Look up a script exporter for this notebook's language\n lang_name = langinfo.get("name")\n if lang_name:\n self.log.debug("Using script exporter for language: %s", lang_name)\n exporter = self._get_language_exporter(lang_name)\n if exporter is not None:\n return exporter.from_notebook_node(nb, resources, **kw)\n\n # Fall back to plain script export\n self.file_extension = langinfo.get("file_extension", ".txt")\n self.output_mimetype = langinfo.get("mimetype", "text/plain")\n return super().from_notebook_node(nb, resources, **kw)\n | .venv\Lib\site-packages\nbconvert\exporters\script.py | script.py | Python | 3,177 | 0.95 | 0.289474 | 0.129032 | awesome-app | 435 | 2024-07-16T08:04:04.136902 | GPL-3.0 | false | 704189594020f5c1b32893f20a17809e |
"""HTML slide show Exporter class"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom copy import deepcopy\nfrom warnings import warn\n\nfrom traitlets import Bool, Unicode, default\n\nfrom nbconvert.preprocessors.base import Preprocessor\n\nfrom .html import HTMLExporter\n\n\nclass _RevealMetadataPreprocessor(Preprocessor):\n # A custom preprocessor adding convenience metadata to cells\n\n def preprocess(self, nb, resources=None):\n nb = deepcopy(nb)\n\n for cell in nb.cells:\n # Make sure every cell has a slide_type\n try:\n slide_type = cell.metadata.get("slideshow", {}).get("slide_type", "-")\n except AttributeError:\n slide_type = "-"\n cell.metadata.slide_type = slide_type\n\n # Find the first visible cell\n for index, cell in enumerate(nb.cells):\n if cell.metadata.slide_type not in {"notes", "skip"}:\n cell.metadata.slide_type = "slide"\n cell.metadata.slide_start = True\n cell.metadata.subslide_start = True\n first_slide_ix = index\n break\n else:\n msg = "All cells are hidden, cannot create slideshow"\n raise ValueError(msg)\n\n in_fragment = False\n\n for index, cell in enumerate(nb.cells[first_slide_ix + 1 :], start=(first_slide_ix + 1)):\n previous_cell = nb.cells[index - 1]\n\n # Slides are <section> elements in the HTML, subslides (the vertically\n # stacked slides) are also <section> elements inside the slides,\n # and fragments are <div>s within subslides. Subslide and fragment\n # elements can contain content:\n # <section>\n # <section>\n # (content)\n # <div class="fragment">(content)</div>\n # </section>\n # </section>\n\n # Get the slide type. If type is subslide or slide,\n # end the last slide/subslide/fragment as applicable.\n if cell.metadata.slide_type == "slide":\n previous_cell.metadata.slide_end = True\n cell.metadata.slide_start = True\n if cell.metadata.slide_type in {"subslide", "slide"}:\n previous_cell.metadata.fragment_end = in_fragment\n previous_cell.metadata.subslide_end = True\n cell.metadata.subslide_start = True\n in_fragment = False\n\n elif cell.metadata.slide_type == "fragment":\n cell.metadata.fragment_start = True\n if in_fragment:\n previous_cell.metadata.fragment_end = True\n else:\n in_fragment = True\n\n # The last cell will always be the end of a slide\n nb.cells[-1].metadata.fragment_end = in_fragment\n nb.cells[-1].metadata.subslide_end = True\n nb.cells[-1].metadata.slide_end = True\n\n return nb, resources\n\n\nclass SlidesExporter(HTMLExporter):\n """Exports HTML slides with reveal.js"""\n\n # Overrides from HTMLExporter\n #################################\n export_from_notebook = "Reveal.js slides"\n\n @default("template_name")\n def _template_name_default(self):\n return "reveal"\n\n @default("file_extension")\n def _file_extension_default(self):\n return ".slides.html"\n\n @default("template_extension")\n def _template_extension_default(self):\n return ".html.j2"\n\n # Extra resources\n #################################\n reveal_url_prefix = Unicode(\n help="""The URL prefix for reveal.js (version 3.x).\n This defaults to the reveal CDN, but can be any url pointing to a copy\n of reveal.js.\n\n For speaker notes to work, this must be a relative path to a local\n copy of reveal.js: e.g., "reveal.js".\n\n If a relative path is given, it must be a subdirectory of the\n current directory (from which the server is run).\n\n See the usage documentation\n (https://nbconvert.readthedocs.io/en/latest/usage.html#reveal-js-html-slideshow)\n for more details.\n """\n ).tag(config=True)\n\n @default("reveal_url_prefix")\n def _reveal_url_prefix_default(self):\n if "RevealHelpPreprocessor.url_prefix" in self.config:\n warn(\n "Please update RevealHelpPreprocessor.url_prefix to "\n "SlidesExporter.reveal_url_prefix in config files.",\n stacklevel=2,\n )\n return self.config.RevealHelpPreprocessor.url_prefix\n return "https://unpkg.com/reveal.js@4.0.2"\n\n reveal_theme = Unicode(\n "simple",\n help="""\n Name of the reveal.js theme to use.\n\n We look for a file with this name under\n ``reveal_url_prefix``/css/theme/``reveal_theme``.css.\n\n https://github.com/hakimel/reveal.js/tree/master/css/theme has\n list of themes that ship by default with reveal.js.\n """,\n ).tag(config=True)\n\n reveal_transition = Unicode(\n "slide",\n help="""\n Name of the reveal.js transition to use.\n\n The list of transitions that ships by default with reveal.js are:\n none, fade, slide, convex, concave and zoom.\n """,\n ).tag(config=True)\n\n reveal_scroll = Bool(\n False,\n help="""\n If True, enable scrolling within each slide\n """,\n ).tag(config=True)\n\n reveal_number = Unicode(\n "",\n help="""\n slide number format (e.g. 'c/t'). Choose from:\n 'c': current, 't': total, 'h': horizontal, 'v': vertical\n """,\n ).tag(config=True)\n\n reveal_width = Unicode(\n "",\n help="""\n width used to determine the aspect ratio of your presentation.\n Use the horizontal pixels available on your intended presentation\n equipment.\n """,\n ).tag(config=True)\n\n reveal_height = Unicode(\n "",\n help="""\n height used to determine the aspect ratio of your presentation.\n Use the horizontal pixels available on your intended presentation\n equipment.\n """,\n ).tag(config=True)\n\n font_awesome_url = Unicode(\n "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css",\n help="""\n URL to load font awesome from.\n\n Defaults to loading from cdnjs.\n """,\n ).tag(config=True)\n\n def _init_resources(self, resources):\n resources = super()._init_resources(resources)\n if "reveal" not in resources:\n resources["reveal"] = {}\n resources["reveal"]["url_prefix"] = self.reveal_url_prefix\n resources["reveal"]["theme"] = self.reveal_theme\n resources["reveal"]["transition"] = self.reveal_transition\n resources["reveal"]["scroll"] = self.reveal_scroll\n resources["reveal"]["number"] = self.reveal_number\n resources["reveal"]["height"] = self.reveal_height\n resources["reveal"]["width"] = self.reveal_width\n return resources\n | .venv\Lib\site-packages\nbconvert\exporters\slides.py | slides.py | Python | 7,099 | 0.95 | 0.110048 | 0.130178 | awesome-app | 314 | 2024-12-15T10:47:36.554407 | MIT | false | 065a6407257ce0f911ffd0894a1bfc69 |
"""This module defines TemplateExporter, a highly configurable converter\nthat uses Jinja2 to export notebook files into different formats.\n"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport html\nimport json\nimport os\nimport typing as t\nimport uuid\nimport warnings\nfrom pathlib import Path\n\nfrom jinja2 import (\n BaseLoader,\n ChoiceLoader,\n DictLoader,\n Environment,\n FileSystemLoader,\n TemplateNotFound,\n)\nfrom jupyter_core.paths import jupyter_path\nfrom nbformat import NotebookNode\nfrom traitlets import Bool, Dict, HasTraits, List, Unicode, default, observe, validate\nfrom traitlets.config import Config\nfrom traitlets.utils.importstring import import_item\n\nfrom nbconvert import filters\n\nfrom .exporter import Exporter\n\n# Jinja2 extensions to load.\nJINJA_EXTENSIONS = ["jinja2.ext.loopcontrols"]\n\nROOT = os.path.dirname(__file__)\nDEV_MODE = os.path.exists(os.path.join(ROOT, "../../.git"))\n\n\ndefault_filters = {\n "indent": filters.indent,\n "markdown2html": filters.markdown2html,\n "markdown2asciidoc": filters.markdown2asciidoc,\n "ansi2html": filters.ansi2html,\n "filter_data_type": filters.DataTypeFilter,\n "get_lines": filters.get_lines,\n "highlight2html": filters.Highlight2HTML,\n "highlight2latex": filters.Highlight2Latex,\n "ipython2python": filters.ipython2python,\n "posix_path": filters.posix_path,\n "markdown2latex": filters.markdown2latex,\n "markdown2rst": filters.markdown2rst,\n "comment_lines": filters.comment_lines,\n "strip_ansi": filters.strip_ansi,\n "strip_dollars": filters.strip_dollars,\n "strip_files_prefix": filters.strip_files_prefix,\n "html2text": filters.html2text,\n "add_anchor": filters.add_anchor,\n "ansi2latex": filters.ansi2latex,\n "wrap_text": filters.wrap_text,\n "escape_latex": filters.escape_latex,\n "citation2latex": filters.citation2latex,\n "path2url": filters.path2url,\n "add_prompts": filters.add_prompts,\n "ascii_only": filters.ascii_only,\n "prevent_list_blocks": filters.prevent_list_blocks,\n "get_metadata": filters.get_metadata,\n "convert_pandoc": filters.convert_pandoc,\n "json_dumps": json.dumps,\n # For removing any HTML\n "escape_html": lambda s: html.escape(str(s)),\n "escape_html_keep_quotes": lambda s: html.escape(str(s), quote=False),\n "escape_html_script": lambda s: s.replace("/", "\\/"),\n # For sanitizing HTML for any XSS\n "clean_html": filters.clean_html,\n "strip_trailing_newline": filters.strip_trailing_newline,\n "text_base64": filters.text_base64,\n}\n\n\n# copy of https://github.com/jupyter/jupyter_server/blob/b62458a7f5ad6b5246d2f142258dedaa409de5d9/jupyter_server/config_manager.py#L19\ndef recursive_update(target, new):\n """Recursively update one dictionary using another.\n None values will delete their keys.\n """\n for k, v in new.items():\n if isinstance(v, dict):\n if k not in target:\n target[k] = {}\n recursive_update(target[k], v)\n if not target[k]:\n # Prune empty subdicts\n del target[k]\n\n elif v is None:\n target.pop(k, None)\n\n else:\n target[k] = v\n return target # return for convenience\n\n\n# define function at the top level to avoid pickle errors\ndef deprecated(msg):\n """Emit a deprecation warning."""\n warnings.warn(msg, DeprecationWarning, stacklevel=2)\n\n\nclass ExtensionTolerantLoader(BaseLoader):\n """A template loader which optionally adds a given extension when searching.\n\n Constructor takes two arguments: *loader* is another Jinja loader instance\n to wrap. *extension* is the extension, which will be added to the template\n name if finding the template without it fails. This should include the dot,\n e.g. '.tpl'.\n """\n\n def __init__(self, loader, extension):\n """Initialize the loader."""\n self.loader = loader\n self.extension = extension\n\n def get_source(self, environment, template):\n """Get the source for a template."""\n try:\n return self.loader.get_source(environment, template)\n except TemplateNotFound:\n if template.endswith(self.extension):\n raise TemplateNotFound(template) from None\n return self.loader.get_source(environment, template + self.extension)\n\n def list_templates(self):\n """List available templates."""\n return self.loader.list_templates()\n\n\nclass TemplateExporter(Exporter):\n """\n Exports notebooks into other file formats. Uses Jinja 2 templating engine\n to output new formats. Inherit from this class if you are creating a new\n template type along with new filters/preprocessors. If the filters/\n preprocessors provided by default suffice, there is no need to inherit from\n this class. Instead, override the template_file and file_extension\n traits via a config file.\n\n Filters available by default for templates:\n\n {filters}\n """\n\n # finish the docstring\n __doc__ = (\n __doc__.format(filters="- " + "\n - ".join(sorted(default_filters.keys())))\n if __doc__\n else None\n )\n\n _template_cached = None\n\n def _invalidate_template_cache(self, change=None):\n self._template_cached = None\n\n @property\n def template(self):\n if self._template_cached is None:\n self._template_cached = self._load_template()\n return self._template_cached\n\n _environment_cached = None\n\n def _invalidate_environment_cache(self, change=None):\n self._environment_cached = None\n self._invalidate_template_cache()\n\n @property\n def environment(self):\n if self._environment_cached is None:\n self._environment_cached = self._create_environment()\n return self._environment_cached\n\n @property\n def default_config(self):\n c = Config(\n {\n "RegexRemovePreprocessor": {"enabled": True},\n "TagRemovePreprocessor": {"enabled": True},\n }\n )\n if super().default_config:\n c2 = super().default_config.copy()\n c2.merge(c)\n c = c2\n return c\n\n template_name = Unicode(help="Name of the template to use").tag(\n config=True, affects_template=True\n )\n\n template_file = Unicode(None, allow_none=True, help="Name of the template file to use").tag(\n config=True, affects_template=True\n )\n\n raw_template = Unicode("", help="raw template string").tag(affects_environment=True)\n\n enable_async = Bool(False, help="Enable Jinja async template execution").tag(\n affects_environment=True\n )\n\n _last_template_file = ""\n _raw_template_key = "<memory>"\n\n @validate("template_name")\n def _template_name_validate(self, change):\n template_name = change["value"]\n if template_name and template_name.endswith(".tpl"):\n warnings.warn(\n f"5.x style template name passed '{self.template_name}'. Use --template-name for the template directory with a index.<ext>.j2 file and/or --template-file to denote a different template.",\n DeprecationWarning,\n stacklevel=2,\n )\n directory, self.template_file = os.path.split(self.template_name)\n if directory:\n directory, template_name = os.path.split(directory)\n if directory and os.path.isabs(directory):\n self.extra_template_basedirs = [directory]\n return template_name\n\n @observe("template_file")\n def _template_file_changed(self, change):\n new = change["new"]\n if new == "default":\n self.template_file = self.default_template # type:ignore[attr-defined]\n return\n # check if template_file is a file path\n # rather than a name already on template_path\n full_path = os.path.abspath(new)\n if os.path.isfile(full_path):\n directory, self.template_file = os.path.split(full_path)\n self.extra_template_paths = [directory, *self.extra_template_paths]\n # While not strictly an invalid template file name, the extension hints that there isn't a template directory involved\n if self.template_file and self.template_file.endswith(".tpl"):\n warnings.warn(\n f"5.x style template file passed '{new}'. Use --template-name for the template directory with a index.<ext>.j2 file and/or --template-file to denote a different template.",\n DeprecationWarning,\n stacklevel=2,\n )\n\n @default("template_file")\n def _template_file_default(self):\n if self.template_extension:\n return "index" + self.template_extension\n return None\n\n @observe("raw_template")\n def _raw_template_changed(self, change):\n if not change["new"]:\n self.template_file = self._last_template_file\n self._invalidate_template_cache()\n\n template_paths = List(["."]).tag(config=True, affects_environment=True)\n extra_template_basedirs = List(Unicode()).tag(config=True, affects_environment=True)\n extra_template_paths = List(Unicode()).tag(config=True, affects_environment=True)\n\n @default("extra_template_basedirs")\n def _default_extra_template_basedirs(self):\n return [os.getcwd()]\n\n # Extension that the template files use.\n template_extension = Unicode().tag(config=True, affects_environment=True)\n\n template_data_paths = List(\n jupyter_path("nbconvert", "templates"), help="Path where templates can be installed too."\n ).tag(affects_environment=True)\n\n @default("template_extension")\n def _template_extension_default(self):\n if self.file_extension:\n return self.file_extension + ".j2"\n return self.file_extension\n\n exclude_input = Bool(\n False, help="This allows you to exclude code cell inputs from all templates if set to True."\n ).tag(config=True)\n\n exclude_input_prompt = Bool(\n False, help="This allows you to exclude input prompts from all templates if set to True."\n ).tag(config=True)\n\n exclude_output = Bool(\n False,\n help="This allows you to exclude code cell outputs from all templates if set to True.",\n ).tag(config=True)\n\n exclude_output_prompt = Bool(\n False, help="This allows you to exclude output prompts from all templates if set to True."\n ).tag(config=True)\n\n exclude_output_stdin = Bool(\n True,\n help="This allows you to exclude output of stdin stream from lab template if set to True.",\n ).tag(config=True)\n\n exclude_code_cell = Bool(\n False, help="This allows you to exclude code cells from all templates if set to True."\n ).tag(config=True)\n\n exclude_markdown = Bool(\n False, help="This allows you to exclude markdown cells from all templates if set to True."\n ).tag(config=True)\n\n exclude_raw = Bool(\n False, help="This allows you to exclude raw cells from all templates if set to True."\n ).tag(config=True)\n\n exclude_unknown = Bool(\n False, help="This allows you to exclude unknown cells from all templates if set to True."\n ).tag(config=True)\n\n extra_loaders: List[t.Any] = List(\n help="Jinja loaders to find templates. Will be tried in order "\n "before the default FileSystem ones.",\n ).tag(affects_environment=True)\n\n filters = Dict(\n help="""Dictionary of filters, by name and namespace, to add to the Jinja\n environment."""\n ).tag(config=True, affects_environment=True)\n\n raw_mimetypes = List(\n Unicode(), help="""formats of raw cells to be included in this Exporter's output."""\n ).tag(config=True)\n\n @default("raw_mimetypes")\n def _raw_mimetypes_default(self):\n return [self.output_mimetype, ""]\n\n # TODO: passing config is wrong, but changing this revealed more complicated issues\n def __init__(self, config=None, **kw):\n """\n Public constructor\n\n Parameters\n ----------\n config : config\n User configuration instance.\n extra_loaders : list[of Jinja Loaders]\n ordered list of Jinja loader to find templates. Will be tried in order\n before the default FileSystem ones.\n template_file : str (optional, kw arg)\n Template to use when exporting.\n """\n super().__init__(config=config, **kw)\n\n self.observe(\n self._invalidate_environment_cache, list(self.traits(affects_environment=True))\n )\n self.observe(self._invalidate_template_cache, list(self.traits(affects_template=True)))\n\n def _load_template(self):\n """Load the Jinja template object from the template file\n\n This is triggered by various trait changes that would change the template.\n """\n\n # this gives precedence to a raw_template if present\n with self.hold_trait_notifications():\n if self.template_file and (self.template_file != self._raw_template_key):\n self._last_template_file = self.template_file\n if self.raw_template:\n self.template_file = self._raw_template_key\n\n if not self.template_file:\n msg = "No template_file specified!"\n raise ValueError(msg)\n\n # First try to load the\n # template by name with extension added, then try loading the template\n # as if the name is explicitly specified.\n template_file = self.template_file\n self.log.debug("Attempting to load template %s", template_file)\n self.log.debug(" template_paths: %s", os.pathsep.join(self.template_paths))\n return self.environment.get_template(template_file)\n\n def from_filename( # type:ignore[override]\n self, filename: str, resources: dict[str, t.Any] | None = None, **kw: t.Any\n ) -> tuple[str, dict[str, t.Any]]:\n """Convert a notebook from a filename."""\n return super().from_filename(filename, resources, **kw) # type:ignore[return-value]\n\n def from_file( # type:ignore[override]\n self, file_stream: t.Any, resources: dict[str, t.Any] | None = None, **kw: t.Any\n ) -> tuple[str, dict[str, t.Any]]:\n """Convert a notebook from a file."""\n return super().from_file(file_stream, resources, **kw) # type:ignore[return-value]\n\n def from_notebook_node( # type:ignore[explicit-override, override]\n self, nb: NotebookNode, resources: dict[str, t.Any] | None = None, **kw: t.Any\n ) -> tuple[str, dict[str, t.Any]]:\n """\n Convert a notebook from a notebook node instance.\n\n Parameters\n ----------\n nb : :class:`~nbformat.NotebookNode`\n Notebook node\n resources : dict\n Additional resources that can be accessed read/write by\n preprocessors and filters.\n """\n nb_copy, resources = super().from_notebook_node(nb, resources, **kw)\n resources.setdefault("raw_mimetypes", self.raw_mimetypes)\n resources.setdefault("output_mimetype", self.output_mimetype)\n resources["global_content_filter"] = {\n "include_code": not self.exclude_code_cell,\n "include_markdown": not self.exclude_markdown,\n "include_raw": not self.exclude_raw,\n "include_unknown": not self.exclude_unknown,\n "include_input": not self.exclude_input,\n "include_output": not self.exclude_output,\n "include_output_stdin": not self.exclude_output_stdin,\n "include_input_prompt": not self.exclude_input_prompt,\n "include_output_prompt": not self.exclude_output_prompt,\n "no_prompt": self.exclude_input_prompt and self.exclude_output_prompt,\n }\n\n # Top level variables are passed to the template_exporter here.\n output = self.template.render(nb=nb_copy, resources=resources)\n output = output.lstrip("\r\n")\n return output, resources\n\n def _register_filter(self, environ, name, jinja_filter):\n """\n Register a filter.\n A filter is a function that accepts and acts on one string.\n The filters are accessible within the Jinja templating engine.\n\n Parameters\n ----------\n name : str\n name to give the filter in the Jinja engine\n filter : filter\n """\n if jinja_filter is None:\n msg = "filter"\n raise TypeError(msg)\n isclass = isinstance(jinja_filter, type)\n constructed = not isclass\n\n # Handle filter's registration based on it's type\n if constructed and isinstance(jinja_filter, (str,)):\n # filter is a string, import the namespace and recursively call\n # this register_filter method\n filter_cls = import_item(jinja_filter)\n return self._register_filter(environ, name, filter_cls)\n\n if constructed and callable(jinja_filter):\n # filter is a function, no need to construct it.\n environ.filters[name] = jinja_filter\n return jinja_filter\n\n if isclass and issubclass(jinja_filter, HasTraits):\n # filter is configurable. Make sure to pass in new default for\n # the enabled flag if one was specified.\n filter_instance = jinja_filter(parent=self)\n self._register_filter(environ, name, filter_instance)\n return None\n\n if isclass:\n # filter is not configurable, construct it\n filter_instance = jinja_filter()\n self._register_filter(environ, name, filter_instance)\n return None\n\n # filter is an instance of something without a __call__\n # attribute.\n msg = "filter"\n raise TypeError(msg)\n\n def register_filter(self, name, jinja_filter):\n """\n Register a filter.\n A filter is a function that accepts and acts on one string.\n The filters are accessible within the Jinja templating engine.\n\n Parameters\n ----------\n name : str\n name to give the filter in the Jinja engine\n filter : filter\n """\n return self._register_filter(self.environment, name, jinja_filter)\n\n def default_filters(self):\n """Override in subclasses to provide extra filters.\n\n This should return an iterable of 2-tuples: (name, class-or-function).\n You should call the method on the parent class and include the filters\n it provides.\n\n If a name is repeated, the last filter provided wins. Filters from\n user-supplied config win over filters provided by classes.\n """\n return default_filters.items()\n\n def _create_environment(self):\n """\n Create the Jinja templating environment.\n """\n paths = self.template_paths\n self.log.debug("Template paths:\n\t%s", "\n\t".join(paths))\n\n loaders = [\n *self.extra_loaders,\n ExtensionTolerantLoader(FileSystemLoader(paths), self.template_extension),\n DictLoader({self._raw_template_key: self.raw_template}),\n ]\n environment = Environment( # noqa: S701\n loader=ChoiceLoader(loaders),\n extensions=JINJA_EXTENSIONS,\n enable_async=self.enable_async,\n )\n\n environment.globals["uuid4"] = uuid.uuid4\n\n # Add default filters to the Jinja2 environment\n for key, value in self.default_filters():\n self._register_filter(environment, key, value)\n\n # Load user filters. Overwrite existing filters if need be.\n if self.filters:\n for key, user_filter in self.filters.items():\n self._register_filter(environment, key, user_filter)\n\n return environment\n\n def _init_preprocessors(self):\n super()._init_preprocessors()\n conf = self._get_conf()\n preprocessors = conf.get("preprocessors", {})\n # preprocessors is a dict for three reasons\n # * We rely on recursive_update, which can only merge dicts, lists will be overwritten\n # * We can use the key with numerical prefixing to guarantee ordering (/etc/*.d/XY-file style)\n # * We can disable preprocessors by overwriting the value with None\n for _, preprocessor in sorted(preprocessors.items(), key=lambda x: x[0]):\n if preprocessor is not None:\n kwargs = preprocessor.copy()\n preprocessor_cls = kwargs.pop("type")\n preprocessor_cls = import_item(preprocessor_cls)\n if preprocessor_cls.__name__ in self.config:\n kwargs.update(self.config[preprocessor_cls.__name__])\n preprocessor = preprocessor_cls(**kwargs) # noqa: PLW2901\n self.register_preprocessor(preprocessor)\n\n def _get_conf(self):\n conf: dict[str, t.Any] = {} # the configuration once all conf files are merged\n for path in map(Path, self.template_paths):\n conf_path = path / "conf.json"\n if conf_path.exists():\n with conf_path.open() as f:\n conf = recursive_update(conf, json.load(f))\n return conf\n\n @default("template_paths")\n def _template_paths(self, prune=True, root_dirs=None):\n paths = []\n root_dirs = self.get_prefix_root_dirs()\n template_names = self.get_template_names()\n for template_name in template_names:\n for base_dir in self.extra_template_basedirs:\n path = os.path.join(base_dir, template_name)\n try:\n if not prune or os.path.exists(path):\n paths.append(path)\n except PermissionError:\n pass\n for root_dir in root_dirs:\n base_dir = os.path.join(root_dir, "nbconvert", "templates")\n path = os.path.join(base_dir, template_name)\n try:\n if not prune or os.path.exists(path):\n paths.append(path)\n except PermissionError:\n pass\n\n for root_dir in root_dirs:\n # we include root_dir for when we want to be very explicit, e.g.\n # {% extends 'nbconvert/templates/classic/base.html' %}\n paths.append(root_dir)\n # we include base_dir for when we want to be explicit, but less than root_dir, e.g.\n # {% extends 'classic/base.html' %}\n base_dir = os.path.join(root_dir, "nbconvert", "templates")\n paths.append(base_dir)\n\n compatibility_dir = os.path.join(root_dir, "nbconvert", "templates", "compatibility")\n paths.append(compatibility_dir)\n\n additional_paths = []\n for path in self.template_data_paths:\n if not prune or os.path.exists(path):\n additional_paths.append(path)\n\n return paths + self.extra_template_paths + additional_paths\n\n @classmethod\n def get_compatibility_base_template_conf(cls, name):\n """Get the base template config."""\n # Hard-coded base template confs to use for backwards compatibility for 5.x-only templates\n if name == "display_priority":\n return {"base_template": "base"}\n if name == "full":\n return {"base_template": "classic", "mimetypes": {"text/html": True}}\n return None\n\n def get_template_names(self):\n """Finds a list of template names where each successive template name is the base template"""\n template_names = []\n root_dirs = self.get_prefix_root_dirs()\n base_template: str | None = self.template_name\n merged_conf: dict[str, t.Any] = {} # the configuration once all conf files are merged\n while base_template is not None:\n template_names.append(base_template)\n conf: dict[str, t.Any] = {}\n found_at_least_one = False\n for base_dir in self.extra_template_basedirs:\n template_dir = os.path.join(base_dir, base_template)\n if os.path.exists(template_dir):\n found_at_least_one = True\n conf_file = os.path.join(template_dir, "conf.json")\n if os.path.exists(conf_file):\n with open(conf_file) as f:\n conf = recursive_update(json.load(f), conf)\n for root_dir in root_dirs:\n template_dir = os.path.join(root_dir, "nbconvert", "templates", base_template)\n if os.path.exists(template_dir):\n found_at_least_one = True\n conf_file = os.path.join(template_dir, "conf.json")\n if os.path.exists(conf_file):\n with open(conf_file) as f:\n conf = recursive_update(json.load(f), conf)\n if not found_at_least_one:\n # Check for backwards compatibility template names\n for root_dir in root_dirs:\n compatibility_file = base_template + ".tpl"\n compatibility_path = os.path.join(\n root_dir, "nbconvert", "templates", "compatibility", compatibility_file\n )\n if os.path.exists(compatibility_path):\n found_at_least_one = True\n warnings.warn(\n f"5.x template name passed '{self.template_name}'. Use 'lab' or 'classic' for new template usage.",\n DeprecationWarning,\n stacklevel=2,\n )\n self.template_file = compatibility_file\n conf = self.get_compatibility_base_template_conf(base_template)\n self.template_name = t.cast(str, conf.get("base_template"))\n break\n if not found_at_least_one:\n paths = "\n\t".join(root_dirs)\n msg = f"No template sub-directory with name {base_template!r} found in the following paths:\n\t{paths}"\n raise ValueError(msg)\n merged_conf = recursive_update(dict(conf), merged_conf)\n base_template = t.cast(t.Any, conf.get("base_template"))\n conf = merged_conf\n mimetypes = [mimetype for mimetype, enabled in conf.get("mimetypes", {}).items() if enabled]\n if self.output_mimetype and self.output_mimetype not in mimetypes and mimetypes:\n supported_mimetypes = "\n\t".join(mimetypes)\n msg = f"Unsupported mimetype {self.output_mimetype!r} for template {self.template_name!r}, mimetypes supported are: \n\t{supported_mimetypes}"\n raise ValueError(msg)\n return template_names\n\n def get_prefix_root_dirs(self):\n """Get the prefix root dirs."""\n # We look at the usual jupyter locations, and for development purposes also\n # relative to the package directory (first entry, meaning with highest precedence)\n root_dirs = []\n if DEV_MODE:\n root_dirs.append(os.path.abspath(os.path.join(ROOT, "..", "..", "share", "jupyter")))\n root_dirs.extend(jupyter_path())\n return root_dirs\n\n def _init_resources(self, resources):\n resources = super()._init_resources(resources)\n resources["deprecated"] = deprecated\n return resources\n | .venv\Lib\site-packages\nbconvert\exporters\templateexporter.py | templateexporter.py | Python | 27,557 | 0.95 | 0.20524 | 0.073504 | awesome-app | 468 | 2023-09-04T00:43:17.683687 | GPL-3.0 | false | 3dd5491243e0b4b1fc3d4327276046e4 |
"""Export to PDF via a headless browser"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport asyncio\nimport concurrent.futures\nimport os\nimport subprocess\nimport sys\nimport tempfile\nfrom importlib import util as importlib_util\n\nfrom traitlets import Bool, default\n\nfrom .html import HTMLExporter\n\nPLAYWRIGHT_INSTALLED = importlib_util.find_spec("playwright") is not None\nIS_WINDOWS = os.name == "nt"\n\n\nclass WebPDFExporter(HTMLExporter):\n """Writer designed to write to PDF files.\n\n This inherits from :class:`HTMLExporter`. It creates the HTML using the\n template machinery, and then run playwright to create a pdf.\n """\n\n export_from_notebook = "PDF via HTML"\n\n allow_chromium_download = Bool(\n False,\n help="Whether to allow downloading Chromium if no suitable version is found on the system.",\n ).tag(config=True)\n\n paginate = Bool(\n True,\n help="""\n Split generated notebook into multiple pages.\n\n If False, a PDF with one long page will be generated.\n\n Set to True to match behavior of LaTeX based PDF generator\n """,\n ).tag(config=True)\n\n @default("file_extension")\n def _file_extension_default(self):\n return ".html"\n\n @default("template_name")\n def _template_name_default(self):\n return "webpdf"\n\n disable_sandbox = Bool(\n False,\n help="""\n Disable chromium security sandbox when converting to PDF.\n\n WARNING: This could cause arbitrary code execution in specific circumstances,\n where JS in your notebook can execute serverside code! Please use with\n caution.\n\n ``https://github.com/puppeteer/puppeteer/blob/main@%7B2020-12-14T17:22:24Z%7D/docs/troubleshooting.md#setting-up-chrome-linux-sandbox``\n has more information.\n\n This is required for webpdf to work inside most container environments.\n """,\n ).tag(config=True)\n\n def run_playwright(self, html):\n """Run playwright."""\n\n async def main(temp_file):\n """Run main playwright script."""\n args = ["--no-sandbox"] if self.disable_sandbox else []\n try:\n from playwright.async_api import async_playwright # type: ignore[import-not-found]\n except ModuleNotFoundError as e:\n msg = (\n "Playwright is not installed to support Web PDF conversion. "\n "Please install `nbconvert[webpdf]` to enable."\n )\n raise RuntimeError(msg) from e\n\n if self.allow_chromium_download:\n cmd = [sys.executable, "-m", "playwright", "install", "chromium"]\n subprocess.check_call(cmd) # noqa: S603\n\n playwright = await async_playwright().start()\n chromium = playwright.chromium\n\n try:\n browser = await chromium.launch(\n handle_sigint=False, handle_sigterm=False, handle_sighup=False, args=args\n )\n except Exception as e:\n msg = (\n "No suitable chromium executable found on the system. "\n "Please use '--allow-chromium-download' to allow downloading one,"\n "or install it using `playwright install chromium`."\n )\n await playwright.stop()\n raise RuntimeError(msg) from e\n\n page = await browser.new_page()\n await page.emulate_media(media="print")\n await page.wait_for_timeout(100)\n await page.goto(f"file://{temp_file.name}", wait_until="networkidle")\n await page.wait_for_timeout(100)\n\n pdf_params = {"print_background": True}\n if not self.paginate:\n # Floating point precision errors cause the printed\n # PDF from spilling over a new page by a pixel fraction.\n dimensions = await page.evaluate(\n """() => {\n const rect = document.body.getBoundingClientRect();\n return {\n width: Math.ceil(rect.width) + 1,\n height: Math.ceil(rect.height) + 1,\n }\n }"""\n )\n width = dimensions["width"]\n height = dimensions["height"]\n # 200 inches is the maximum size for Adobe Acrobat Reader.\n pdf_params.update(\n {\n "width": min(width, 200 * 72),\n "height": min(height, 200 * 72),\n }\n )\n pdf_data = await page.pdf(**pdf_params)\n\n await browser.close()\n await playwright.stop()\n return pdf_data\n\n pool = concurrent.futures.ThreadPoolExecutor()\n # Create a temporary file to pass the HTML code to Chromium:\n # Unfortunately, tempfile on Windows does not allow for an already open\n # file to be opened by a separate process. So we must close it first\n # before calling Chromium. We also specify delete=False to ensure the\n # file is not deleted after closing (the default behavior).\n temp_file = tempfile.NamedTemporaryFile(suffix=".html", delete=False)\n with temp_file:\n temp_file.write(html.encode("utf-8"))\n try:\n # TODO: when dropping Python 3.6, use\n # pdf_data = pool.submit(asyncio.run, main(temp_file)).result()\n def run_coroutine(coro):\n """Run an internal coroutine."""\n loop = (\n asyncio.ProactorEventLoop() # type:ignore[attr-defined]\n if IS_WINDOWS\n else asyncio.new_event_loop()\n )\n\n asyncio.set_event_loop(loop)\n return loop.run_until_complete(coro)\n\n pdf_data = pool.submit(run_coroutine, main(temp_file)).result()\n finally:\n # Ensure the file is deleted even if playwright raises an exception\n os.unlink(temp_file.name)\n return pdf_data\n\n def from_notebook_node(self, nb, resources=None, **kw):\n """Convert from a notebook node."""\n html, resources = super().from_notebook_node(nb, resources=resources, **kw)\n\n self.log.info("Building PDF")\n pdf_data = self.run_playwright(html)\n self.log.info("PDF successfully created")\n\n # convert output extension to pdf\n # the writer above required it to be html\n resources["output_extension"] = ".pdf"\n\n return pdf_data, resources\n | .venv\Lib\site-packages\nbconvert\exporters\webpdf.py | webpdf.py | Python | 6,678 | 0.95 | 0.110497 | 0.102041 | vue-tools | 756 | 2024-07-28T21:34:09.756661 | MIT | false | 012d3e4a764449230e5ce0289d58d459 |
from .asciidoc import ASCIIDocExporter\nfrom .base import ExporterDisabledError, ExporterNameError, export, get_export_names, get_exporter\nfrom .exporter import Exporter, FilenameExtension, ResourcesDict\nfrom .html import HTMLExporter\nfrom .latex import LatexExporter\nfrom .markdown import MarkdownExporter\nfrom .notebook import NotebookExporter\nfrom .pdf import PDFExporter\nfrom .python import PythonExporter\nfrom .qtpdf import QtPDFExporter\nfrom .qtpng import QtPNGExporter\nfrom .rst import RSTExporter\nfrom .script import ScriptExporter\nfrom .slides import SlidesExporter\nfrom .templateexporter import TemplateExporter\nfrom .webpdf import WebPDFExporter\n\n__all__ = [\n "ASCIIDocExporter",\n "ExporterNameError",\n "ExporterDisabledError",\n "export",\n "get_export_names",\n "get_exporter",\n "Exporter",\n "FilenameExtension",\n "HTMLExporter",\n "LatexExporter",\n "MarkdownExporter",\n "NotebookExporter",\n "PDFExporter",\n "PythonExporter",\n "QtPDFExporter",\n "QtPNGExporter",\n "ResourcesDict",\n "RSTExporter",\n "ScriptExporter",\n "SlidesExporter",\n "TemplateExporter",\n "WebPDFExporter",\n]\n | .venv\Lib\site-packages\nbconvert\exporters\__init__.py | __init__.py | Python | 1,150 | 0.85 | 0 | 0 | node-utils | 934 | 2024-08-13T23:12:35.947788 | GPL-3.0 | false | fd55294811d5f6f63ea3e81e9afca83d |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\asciidoc.cpython-313.pyc | asciidoc.cpython-313.pyc | Other | 2,197 | 0.8 | 0.034483 | 0 | node-utils | 750 | 2025-01-30T17:49:25.780910 | GPL-3.0 | false | 4dbb56a11d4bdbfe03e6a2d2a9cb9e90 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\base.cpython-313.pyc | base.cpython-313.pyc | Other | 6,106 | 0.95 | 0.107143 | 0 | node-utils | 547 | 2023-08-11T20:21:32.371684 | MIT | false | aac0e4171801f6a9f06d88fbd3a94751 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\exporter.cpython-313.pyc | exporter.cpython-313.pyc | Other | 13,345 | 0.95 | 0.027473 | 0.005952 | awesome-app | 847 | 2023-08-20T01:53:06.253781 | MIT | false | 34d3ce304e7bf2a169367b403be4256a |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\html.cpython-313.pyc | html.cpython-313.pyc | Other | 17,040 | 0.95 | 0.079096 | 0.024242 | vue-tools | 125 | 2024-06-22T21:54:03.626437 | BSD-3-Clause | false | c5d192ab6e6fc16d484045fe1e413d05 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\latex.cpython-313.pyc | latex.cpython-313.pyc | Other | 4,690 | 0.95 | 0.065217 | 0 | vue-tools | 126 | 2023-08-25T14:38:59.797440 | GPL-3.0 | false | 7e160affb0960274e84b6ebb567fb508 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\markdown.cpython-313.pyc | markdown.cpython-313.pyc | Other | 2,200 | 0.8 | 0.034483 | 0 | awesome-app | 631 | 2024-03-10T08:04:52.598397 | Apache-2.0 | false | 74fcf2cb41f472337a08870ef10ca928 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\notebook.cpython-313.pyc | notebook.cpython-313.pyc | Other | 2,196 | 0.8 | 0.038462 | 0 | awesome-app | 859 | 2023-11-01T07:01:23.936177 | Apache-2.0 | false | 8ccf8682425ba34034be8ee844a4b687 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\pdf.cpython-313.pyc | pdf.cpython-313.pyc | Other | 10,497 | 0.95 | 0.048387 | 0.026549 | python-kit | 367 | 2025-06-23T15:26:57.822394 | BSD-3-Clause | false | 457c189e7aed45e256ea1f0a86902c1e |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\python.cpython-313.pyc | python.cpython-313.pyc | Other | 1,254 | 0.8 | 0.066667 | 0 | react-lib | 742 | 2024-02-26T18:21:52.129413 | Apache-2.0 | false | 291761ef5a2526a3c6917c2eaf831cbd |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\qtpdf.cpython-313.pyc | qtpdf.cpython-313.pyc | Other | 1,150 | 0.8 | 0.047619 | 0 | react-lib | 11 | 2024-10-07T19:43:15.472378 | Apache-2.0 | false | c895a1e24372f2a325f2df3be3217653 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\qtpng.cpython-313.pyc | qtpng.cpython-313.pyc | Other | 796 | 0.7 | 0.083333 | 0 | vue-tools | 255 | 2024-07-16T06:09:25.280732 | BSD-3-Clause | false | b749b3721dc7ce8539dcaac6515ab0b9 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\qt_exporter.cpython-313.pyc | qt_exporter.cpython-313.pyc | Other | 3,689 | 0.8 | 0 | 0 | awesome-app | 156 | 2023-12-08T00:13:03.899672 | GPL-3.0 | false | dacaa0121f72793443fec82bdda8a88e |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\qt_screenshot.cpython-313.pyc | qt_screenshot.cpython-313.pyc | Other | 5,634 | 0.8 | 0 | 0 | node-utils | 651 | 2023-10-20T20:47:09.279558 | BSD-3-Clause | false | bbf98a6c9b54109d1c579b1c58b3c409 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\rst.cpython-313.pyc | rst.cpython-313.pyc | Other | 2,650 | 0.8 | 0.033333 | 0 | vue-tools | 110 | 2023-08-30T05:05:25.281526 | MIT | false | 29e0f07531eb44d0cbc526bc670a51b0 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\script.cpython-313.pyc | script.cpython-313.pyc | Other | 3,919 | 0.95 | 0.135135 | 0 | node-utils | 420 | 2025-02-27T05:53:31.003060 | BSD-3-Clause | false | e3c5166005b1680af570dfb715fd8c04 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\slides.cpython-313.pyc | slides.cpython-313.pyc | Other | 7,949 | 0.8 | 0.027211 | 0 | awesome-app | 401 | 2024-06-04T00:01:14.579315 | GPL-3.0 | false | 836889d5e41f14ea68620736ea13a991 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\templateexporter.cpython-313.pyc | templateexporter.cpython-313.pyc | Other | 32,959 | 0.95 | 0.082143 | 0.011407 | react-lib | 759 | 2024-04-28T15:22:01.859667 | Apache-2.0 | false | 365b7760804328189ad2f242b002e440 |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\webpdf.cpython-313.pyc | webpdf.cpython-313.pyc | Other | 8,186 | 0.95 | 0.029126 | 0 | node-utils | 218 | 2024-09-05T16:20:00.872156 | MIT | false | ecb78a8920ce3635b99b912d4186a29d |
\n\n | .venv\Lib\site-packages\nbconvert\exporters\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 1,224 | 0.8 | 0 | 0 | awesome-app | 697 | 2024-11-13T00:22:39.781771 | BSD-3-Clause | false | 9a0feaf39d4ba9508f98355045672c74 |
"""Filters for processing ANSI colors within Jinja templates."""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport re\n\nimport markupsafe\n\n__all__ = ["strip_ansi", "ansi2html", "ansi2latex"]\n\n_ANSI_RE = re.compile("\x1b\\[(.*?)([@-~])")\n\n_ANSI_COLORS = (\n "ansi-black",\n "ansi-red",\n "ansi-green",\n "ansi-yellow",\n "ansi-blue",\n "ansi-magenta",\n "ansi-cyan",\n "ansi-white",\n "ansi-black-intense",\n "ansi-red-intense",\n "ansi-green-intense",\n "ansi-yellow-intense",\n "ansi-blue-intense",\n "ansi-magenta-intense",\n "ansi-cyan-intense",\n "ansi-white-intense",\n)\n\n\ndef strip_ansi(source):\n """\n Remove ANSI escape codes from text.\n\n Parameters\n ----------\n source : str\n Source to remove the ANSI from\n\n """\n return _ANSI_RE.sub("", source)\n\n\ndef ansi2html(text):\n """\n Convert ANSI colors to HTML colors.\n\n Parameters\n ----------\n text : unicode\n Text containing ANSI colors to convert to HTML\n\n """\n text = markupsafe.escape(text)\n return _ansi2anything(text, _htmlconverter)\n\n\ndef ansi2latex(text):\n """\n Convert ANSI colors to LaTeX colors.\n\n Parameters\n ----------\n text : unicode\n Text containing ANSI colors to convert to LaTeX\n\n """\n return _ansi2anything(text, _latexconverter)\n\n\ndef _htmlconverter(fg, bg, bold, underline, inverse):\n """\n Return start and end tags for given foreground/background/bold/underline.\n\n """\n if (fg, bg, bold, underline, inverse) == (None, None, False, False, False):\n return "", ""\n\n classes = []\n styles = []\n\n if inverse:\n fg, bg = bg, fg\n\n if isinstance(fg, int):\n classes.append(_ANSI_COLORS[fg] + "-fg")\n elif fg:\n styles.append("color: rgb({},{},{})".format(*fg))\n elif inverse:\n classes.append("ansi-default-inverse-fg")\n\n if isinstance(bg, int):\n classes.append(_ANSI_COLORS[bg] + "-bg")\n elif bg:\n styles.append("background-color: rgb({},{},{})".format(*bg))\n elif inverse:\n classes.append("ansi-default-inverse-bg")\n\n if bold:\n classes.append("ansi-bold")\n\n if underline:\n classes.append("ansi-underline")\n\n starttag = "<span"\n if classes:\n starttag += ' class="' + " ".join(classes) + '"'\n if styles:\n starttag += ' style="' + "; ".join(styles) + '"'\n starttag += ">"\n return starttag, "</span>"\n\n\ndef _latexconverter(fg, bg, bold, underline, inverse):\n """\n Return start and end markup given foreground/background/bold/underline.\n\n """\n if (fg, bg, bold, underline, inverse) == (None, None, False, False, False):\n return "", ""\n\n starttag, endtag = "", ""\n\n if inverse:\n fg, bg = bg, fg\n\n if isinstance(fg, int):\n starttag += r"\textcolor{" + _ANSI_COLORS[fg] + "}{"\n endtag = "}" + endtag\n elif fg:\n # See http://tex.stackexchange.com/a/291102/13684\n starttag += r"\def\tcRGB{\textcolor[RGB]}\expandafter"\n starttag += r"\tcRGB\expandafter{{\detokenize{{{},{},{}}}}}{{".format(*fg)\n endtag = "}" + endtag\n elif inverse:\n starttag += r"\textcolor{ansi-default-inverse-fg}{"\n endtag = "}" + endtag\n\n if isinstance(bg, int):\n starttag += r"\setlength{\fboxsep}{0pt}"\n starttag += r"\colorbox{" + _ANSI_COLORS[bg] + "}{"\n endtag = r"\strut}" + endtag\n elif bg:\n starttag += r"\setlength{\fboxsep}{0pt}"\n # See http://tex.stackexchange.com/a/291102/13684\n starttag += r"\def\cbRGB{\colorbox[RGB]}\expandafter"\n starttag += r"\cbRGB\expandafter{{\detokenize{{{},{},{}}}}}{{".format(*bg)\n endtag = r"\strut}" + endtag\n elif inverse:\n starttag += r"\setlength{\fboxsep}{0pt}"\n starttag += r"\colorbox{ansi-default-inverse-bg}{"\n endtag = r"\strut}" + endtag\n\n if bold:\n starttag += r"\textbf{"\n endtag = "}" + endtag\n\n if underline:\n starttag += r"\underline{"\n endtag = "}" + endtag\n\n return starttag, endtag\n\n\ndef _ansi2anything(text, converter):\n r"""\n Convert ANSI colors to HTML or LaTeX.\n\n See https://en.wikipedia.org/wiki/ANSI_escape_code\n\n Accepts codes like '\x1b[32m' (red) and '\x1b[1;32m' (bold, red).\n\n Non-color escape sequences (not ending with 'm') are filtered out.\n\n Ideally, this should have the same behavior as the function\n fixConsole() in notebook/notebook/static/base/js/utils.js.\n\n """\n fg, bg = None, None\n bold = False\n underline = False\n inverse = False\n numbers = []\n out = []\n\n while text:\n m = _ANSI_RE.search(text)\n if m:\n if m.group(2) == "m":\n try:\n # Empty code is same as code 0\n numbers = [int(n) if n else 0 for n in m.group(1).split(";")]\n except ValueError:\n pass # Invalid color specification\n else:\n pass # Not a color code\n chunk, text = text[: m.start()], text[m.end() :]\n else:\n chunk, text = text, ""\n\n if chunk:\n starttag, endtag = converter(\n fg + 8 if bold and fg in range(8) else fg, # type:ignore[operator]\n bg,\n bold,\n underline,\n inverse,\n )\n out.append(starttag)\n out.append(chunk)\n out.append(endtag)\n\n while numbers:\n n = numbers.pop(0)\n if n == 0:\n # Code 0 (same as empty code): reset everything\n fg = bg = None\n bold = underline = inverse = False\n elif n == 1:\n bold = True\n elif n == 4:\n underline = True\n elif n == 5:\n # Code 5: blinking\n bold = True\n elif n == 7:\n inverse = True\n elif n in (21, 22):\n bold = False\n elif n == 24:\n underline = False\n elif n == 27:\n inverse = False\n elif 30 <= n <= 37:\n fg = n - 30\n elif n == 38:\n try:\n fg = _get_extended_color(numbers)\n except ValueError:\n numbers.clear()\n elif n == 39:\n fg = None\n elif 40 <= n <= 47:\n bg = n - 40\n elif n == 48:\n try:\n bg = _get_extended_color(numbers)\n except ValueError:\n numbers.clear()\n elif n == 49:\n bg = None\n elif 90 <= n <= 97:\n fg = n - 90 + 8\n elif 100 <= n <= 107:\n bg = n - 100 + 8\n else:\n pass # Unknown codes are ignored\n return "".join(out)\n\n\ndef _get_extended_color(numbers):\n n = numbers.pop(0)\n if n == 2 and len(numbers) >= 3:\n # 24-bit RGB\n r = numbers.pop(0)\n g = numbers.pop(0)\n b = numbers.pop(0)\n if not all(0 <= c <= 255 for c in (r, g, b)):\n raise ValueError()\n elif n == 5 and len(numbers) >= 1:\n # 256 colors\n idx = numbers.pop(0)\n if idx < 0:\n raise ValueError()\n if idx < 16:\n # 16 default terminal colors\n return idx\n if idx < 232:\n # 6x6x6 color cube, see http://stackoverflow.com/a/27165165/500098\n r = (idx - 16) // 36\n r = 55 + r * 40 if r > 0 else 0\n g = ((idx - 16) % 36) // 6\n g = 55 + g * 40 if g > 0 else 0\n b = (idx - 16) % 6\n b = 55 + b * 40 if b > 0 else 0\n elif idx < 256:\n # grayscale, see http://stackoverflow.com/a/27165165/500098\n r = g = b = (idx - 232) * 10 + 8\n else:\n raise ValueError()\n else:\n raise ValueError()\n return r, g, b\n | .venv\Lib\site-packages\nbconvert\filters\ansi.py | ansi.py | Python | 8,042 | 0.95 | 0.162162 | 0.04878 | react-lib | 656 | 2024-12-31T02:59:49.035691 | MIT | false | 247fa51c268cfcdecc5b9e50b80549ee |
"""Citation handling for LaTeX output."""\n\n# -----------------------------------------------------------------------------\n# Copyright (c) 2013, the IPython Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# -----------------------------------------------------------------------------\n\n# -----------------------------------------------------------------------------\n# Imports\n# -----------------------------------------------------------------------------\nfrom html.parser import HTMLParser\n\n# -----------------------------------------------------------------------------\n# Functions\n# -----------------------------------------------------------------------------\n\n__all__ = ["citation2latex"]\n\n\ndef citation2latex(s):\n """Parse citations in Markdown cells.\n\n This looks for HTML tags having a data attribute names ``data-cite``\n and replaces it by the call to LaTeX cite command. The transformation\n looks like this::\n\n <cite data-cite="granger">(Granger, 2013)</cite>\n\n Becomes ::\n\n \\cite{granger}\n\n Any HTML tag can be used, which allows the citations to be formatted\n in HTML in any manner.\n """\n parser = CitationParser()\n parser.feed(s)\n parser.close()\n outtext = ""\n startpos = 0\n for citation in parser.citelist:\n outtext += s[startpos : citation[1]]\n outtext += "\\cite{%s}" % citation[0]\n startpos = citation[2] if len(citation) == 3 else -1\n outtext += s[startpos:] if startpos != -1 else ""\n return outtext\n\n\n# -----------------------------------------------------------------------------\n# Classes\n# -----------------------------------------------------------------------------\nclass CitationParser(HTMLParser):\n """Citation Parser\n\n Replaces html tags with data-cite attribute with respective latex \\cite.\n\n Inherites from HTMLParser, overrides:\n - handle_starttag\n - handle_endtag\n """\n\n # number of open tags\n opentags = None\n # list of found citations\n citelist = None # type:ignore[var-annotated]\n # active citation tag\n citetag = None\n\n def __init__(self):\n """Initialize the parser."""\n self.citelist = []\n self.opentags = 0\n HTMLParser.__init__(self)\n\n def get_offset(self):\n """Get the offset position."""\n # Compute startposition in source\n lin, offset = self.getpos()\n pos = 0\n for _ in range(lin - 1):\n pos = self.data.find("\n", pos) + 1\n return pos + offset\n\n def handle_starttag(self, tag, attrs):\n """Handle a start tag."""\n # for each tag check if attributes are present and if no citation is active\n if self.opentags == 0 and len(attrs) > 0:\n for atr, data in attrs:\n if atr.lower() == "data-cite":\n self.citetag = tag\n self.opentags = 1\n self.citelist.append([data, self.get_offset()])\n return\n\n if tag == self.citetag:\n # found an open citation tag but not the starting one\n self.opentags += 1 # type:ignore[operator]\n\n def handle_endtag(self, tag):\n """Handle an end tag."""\n if tag == self.citetag:\n # found citation tag check if starting one\n if self.opentags == 1:\n pos = self.get_offset()\n self.citelist[-1].append(pos + len(tag) + 3)\n self.opentags -= 1 # type:ignore[operator]\n\n def feed(self, data):\n """Handle a feed."""\n self.data = data\n HTMLParser.feed(self, data)\n | .venv\Lib\site-packages\nbconvert\filters\citation.py | citation.py | Python | 3,694 | 0.95 | 0.201754 | 0.25 | awesome-app | 22 | 2025-05-16T09:03:16.592753 | Apache-2.0 | false | 870853d087bf903414948847db1a6b91 |
"""Filter used to select the first preferred output format available.\n\nThe filter contained in the file allows the converter templates to select\nthe output format that is most valuable to the active export format. The\nvalue of the different formats is set via\nNbConvertBase.display_data_priority\n"""\n# -----------------------------------------------------------------------------\n# Copyright (c) 2013, the IPython Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# -----------------------------------------------------------------------------\n\n# -----------------------------------------------------------------------------\n# Classes and functions\n# -----------------------------------------------------------------------------\n\nfrom warnings import warn\n\nfrom nbconvert.utils.base import NbConvertBase\n\n__all__ = ["DataTypeFilter"]\n\n\nclass DataTypeFilter(NbConvertBase):\n """Returns the preferred display format"""\n\n def __call__(self, output):\n """Return the first available format in the priority.\n\n Produces a UserWarning if no compatible mimetype is found.\n\n `output` is dict with structure {mimetype-of-element: value-of-element}\n\n """\n for fmt in self.display_data_priority:\n if fmt in output:\n return [fmt]\n warn(\n f"Your element with mimetype(s) {output.keys()} is not able to be represented.",\n stacklevel=2,\n )\n\n return []\n | .venv\Lib\site-packages\nbconvert\filters\datatypefilter.py | datatypefilter.py | Python | 1,556 | 0.95 | 0.108696 | 0.294118 | node-utils | 224 | 2025-04-27T06:52:58.539859 | GPL-3.0 | false | 069c2e9e36a08bd02581546572fe231f |
"""A pandoc filter used in converting notebooks to Latex.\nConverts links between notebooks to Latex cross-references.\n"""\n\nimport re\n\nfrom pandocfilters import RawInline, applyJSONFilters, stringify # type:ignore[import-untyped]\n\n\ndef resolve_references(source):\n """\n This applies the resolve_one_reference to the text passed in via the source argument.\n\n This expects content in the form of a string encoded JSON object as represented\n internally in ``pandoc``.\n """\n return applyJSONFilters([resolve_one_reference], source)\n\n\ndef resolve_one_reference(key, val, fmt, meta):\n """\n This takes a tuple of arguments that are compatible with ``pandocfilters.walk()`` that\n allows identifying hyperlinks in the document and transforms them into valid LaTeX\n \\hyperref{} calls so that linking to headers between cells is possible.\n\n See the documentation in ``pandocfilters.walk()`` for further information on the meaning\n and specification of ``key``, ``val``, ``fmt``, and ``meta``.\n """\n\n if key == "Link":\n text = stringify(val[1])\n target = val[2][0]\n m = re.match(r"#(.+)$", target)\n if m:\n # pandoc automatically makes labels for headings.\n label = m.group(1).lower()\n label = re.sub(r"[^\w-]+", "", label) # Strip HTML entities\n text = re.sub(r"_", r"\_", text) # Escape underscores in display text\n return RawInline("tex", rf"\hyperref[{label}]{{{text}}}")\n return None\n # Other elements will be returned unchanged.\n | .venv\Lib\site-packages\nbconvert\filters\filter_links.py | filter_links.py | Python | 1,556 | 0.95 | 0.146341 | 0.0625 | awesome-app | 170 | 2025-05-06T15:46:49.530187 | MIT | false | 5e2406e6f5115de0870dd8740cef9964 |
"""\nModule containing filter functions that allow code to be highlighted\nfrom within Jinja templates.\n"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n# pygments must not be imported at the module level\n# because errors should be raised at runtime if it's actually needed,\n# not import time, when it may not be needed.\n\nfrom html import escape\nfrom warnings import warn\n\nfrom traitlets import Dict, observe\n\nfrom nbconvert.utils.base import NbConvertBase\n\nMULTILINE_OUTPUTS = ["text", "html", "svg", "latex", "javascript", "json"]\n\n__all__ = ["Highlight2HTML", "Highlight2Latex"]\n\n\nclass Highlight2HTML(NbConvertBase):\n """Convert highlighted code to html."""\n\n extra_formatter_options = Dict(\n {},\n help="""\n Extra set of options to control how code is highlighted.\n\n Passed through to the pygments' HtmlFormatter class.\n See available list in https://pygments.org/docs/formatters/#HtmlFormatter\n """,\n config=True,\n )\n\n def __init__(self, pygments_lexer=None, **kwargs):\n """Initialize the converter."""\n self.pygments_lexer = pygments_lexer or "ipython3"\n super().__init__(**kwargs)\n\n @observe("default_language")\n def _default_language_changed(self, change):\n warn(\n "Setting default_language in config is deprecated as of 5.0, "\n "please use language_info metadata instead.",\n stacklevel=2,\n )\n self.pygments_lexer = change["new"]\n\n def __call__(self, source, language=None, metadata=None):\n """\n Return a syntax-highlighted version of the input source as html output.\n\n Parameters\n ----------\n source : str\n source of the cell to highlight\n language : str\n language to highlight the syntax of\n metadata : NotebookNode cell metadata\n metadata of the cell to highlight\n """\n from pygments.formatters import HtmlFormatter\n\n if not language:\n language = self.pygments_lexer\n\n return _pygments_highlight(\n source if len(source) > 0 else " ",\n # needed to help post processors:\n HtmlFormatter(\n cssclass=escape(f" highlight hl-{language}"), **self.extra_formatter_options\n ),\n language,\n metadata,\n )\n\n\nclass Highlight2Latex(NbConvertBase):\n """Convert highlighted code to latex."""\n\n extra_formatter_options = Dict(\n {},\n help="""\n Extra set of options to control how code is highlighted.\n\n Passed through to the pygments' LatexFormatter class.\n See available list in https://pygments.org/docs/formatters/#LatexFormatter\n """,\n config=True,\n )\n\n def __init__(self, pygments_lexer=None, **kwargs):\n """Initialize the converter."""\n self.pygments_lexer = pygments_lexer or "ipython3"\n super().__init__(**kwargs)\n\n @observe("default_language")\n def _default_language_changed(self, change):\n warn(\n "Setting default_language in config is deprecated as of 5.0, "\n "please use language_info metadata instead.",\n stacklevel=2,\n )\n self.pygments_lexer = change["new"]\n\n def __call__(self, source, language=None, metadata=None, strip_verbatim=False):\n """\n Return a syntax-highlighted version of the input source as latex output.\n\n Parameters\n ----------\n source : str\n source of the cell to highlight\n language : str\n language to highlight the syntax of\n metadata : NotebookNode cell metadata\n metadata of the cell to highlight\n strip_verbatim : bool\n remove the Verbatim environment that pygments provides by default\n """\n from pygments.formatters import LatexFormatter\n\n if not language:\n language = self.pygments_lexer\n\n latex = _pygments_highlight(\n source, LatexFormatter(**self.extra_formatter_options), language, metadata\n )\n if strip_verbatim:\n latex = latex.replace(r"\begin{Verbatim}[commandchars=\\\{\}]" + "\n", "")\n return latex.replace("\n\\end{Verbatim}\n", "")\n return latex\n\n\ndef _pygments_highlight(\n source, output_formatter, language="ipython", metadata=None, **lexer_options\n):\n """\n Return a syntax-highlighted version of the input source\n\n Parameters\n ----------\n source : str\n source of the cell to highlight\n output_formatter : Pygments formatter\n language : str\n language to highlight the syntax of\n metadata : NotebookNode cell metadata\n metadata of the cell to highlight\n lexer_options : dict\n Options to pass to the pygments lexer. See\n https://pygments.org/docs/lexers/#available-lexers for more information about\n valid lexer options\n """\n from pygments import highlight\n from pygments.lexers import get_lexer_by_name\n from pygments.util import ClassNotFound\n\n # If the cell uses a magic extension language,\n # use the magic language instead.\n if language.startswith("ipython") and metadata and "magics_language" in metadata:\n language = metadata["magics_language"]\n\n lexer = None\n if language == "ipython2":\n try:\n from IPython.lib.lexers import IPythonLexer\n except ImportError:\n warn("IPython lexer unavailable, falling back on Python", stacklevel=2)\n language = "python"\n else:\n lexer = IPythonLexer()\n elif language == "ipython3":\n try:\n from IPython.lib.lexers import IPython3Lexer\n except ImportError:\n warn("IPython3 lexer unavailable, falling back on Python 3", stacklevel=2)\n language = "python3"\n else:\n lexer = IPython3Lexer()\n\n if lexer is None:\n try:\n lexer = get_lexer_by_name(language, **lexer_options)\n except ClassNotFound:\n warn("No lexer found for language %r. Treating as plain text." % language, stacklevel=2)\n from pygments.lexers.special import TextLexer\n\n lexer = TextLexer()\n\n return highlight(source, lexer, output_formatter)\n | .venv\Lib\site-packages\nbconvert\filters\highlight.py | highlight.py | Python | 6,330 | 0.95 | 0.123077 | 0.05 | vue-tools | 88 | 2024-11-05T00:21:18.813161 | GPL-3.0 | false | ec876f8ce45250a7b8cac0a48a8b0ec5 |
"""Latex filters.\n\nModule of useful filters for processing Latex within Jinja latex templates.\n"""\n# -----------------------------------------------------------------------------\n# Copyright (c) 2013, the IPython Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# -----------------------------------------------------------------------------\n\n# -----------------------------------------------------------------------------\n# Imports\n# -----------------------------------------------------------------------------\nimport re\n\n# -----------------------------------------------------------------------------\n# Globals and constants\n# -----------------------------------------------------------------------------\n\nLATEX_RE_SUBS = ((re.compile(r"\.\.\.+"), r"{\\ldots}"),)\n\n# Latex substitutions for escaping latex.\n# see: http://stackoverflow.com/questions/16259923/how-can-i-escape-latex-special-characters-inside-django-templates\n\nLATEX_SUBS = {\n "&": r"\&",\n "%": r"\%",\n "$": r"\$",\n "#": r"\#",\n "_": r"\_",\n "{": r"\{",\n "}": r"\}",\n "~": r"\textasciitilde{}",\n "^": r"\^{}",\n "\\": r"\textbackslash{}",\n}\n\n\n# -----------------------------------------------------------------------------\n# Functions\n# -----------------------------------------------------------------------------\n\n__all__ = ["escape_latex"]\n\n\ndef escape_latex(text):\n """\n Escape characters that may conflict with latex.\n\n Parameters\n ----------\n text : str\n Text containing characters that may conflict with Latex\n """\n text = "".join(LATEX_SUBS.get(c, c) for c in text)\n for pattern, replacement in LATEX_RE_SUBS:\n text = pattern.sub(replacement, text)\n\n return text\n | .venv\Lib\site-packages\nbconvert\filters\latex.py | latex.py | Python | 1,819 | 0.95 | 0.081967 | 0.375 | awesome-app | 666 | 2023-08-06T04:21:19.453001 | Apache-2.0 | false | 2c97de67408e27caf9878fefdbbdcbd8 |
"""Markdown filters\n\nThis file contains a collection of utility filters for dealing with\nmarkdown within Jinja templates.\n"""\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport re\n\nfrom packaging.version import Version\n\nfrom nbconvert.utils.pandoc import get_pandoc_version\n\ntry:\n from .markdown_mistune import markdown2html_mistune\n\nexcept ImportError as e:\n _mistune_import_error = e\n\n def markdown2html_mistune(source: str) -> str:\n """mistune is unavailable, raise ImportError"""\n msg = f"markdown2html requires mistune: {_mistune_import_error}"\n raise ImportError(msg)\n\n\nfrom .pandoc import convert_pandoc\n\n__all__ = [\n "markdown2html",\n "markdown2html_pandoc",\n "markdown2html_mistune",\n "markdown2latex",\n "markdown2rst",\n "markdown2asciidoc",\n]\n\n\n_MARKDOWN_FMT = "markdown+lists_without_preceding_blankline"\n\n\ndef markdown2latex(source, markup=_MARKDOWN_FMT, extra_args=None):\n """\n Convert a markdown string to LaTeX via pandoc.\n\n This function will raise an error if pandoc is not installed.\n Any error messages generated by pandoc are printed to stderr.\n\n Parameters\n ----------\n source : string\n Input string, assumed to be valid markdown.\n markup : string\n Markup used by pandoc's reader\n default : pandoc extended markdown\n (see https://pandoc.org/README.html#pandocs-markdown)\n\n Returns\n -------\n out : string\n Output as returned by pandoc.\n """\n return convert_pandoc(source, markup, "latex", extra_args=extra_args)\n\n\ndef markdown2html_pandoc(source, extra_args=None):\n """\n Convert a markdown string to HTML via pandoc.\n """\n extra_args = extra_args or ["--mathjax"]\n return convert_pandoc(source, _MARKDOWN_FMT, "html", extra_args=extra_args)\n\n\ndef markdown2asciidoc(source, extra_args=None):\n """Convert a markdown string to asciidoc via pandoc"""\n\n # Prior to version 3.0, pandoc supported the --atx-headers flag.\n # For later versions, we must instead pass --markdown-headings=atx.\n # See https://pandoc.org/releases.html#pandoc-3.0-2023-01-18\n atx_args = ["--atx-headers"]\n pandoc_version = get_pandoc_version()\n if pandoc_version and Version(pandoc_version) >= Version("3.0"):\n atx_args = ["--markdown-headings=atx"]\n\n extra_args = extra_args or atx_args\n asciidoc = convert_pandoc(source, _MARKDOWN_FMT, "asciidoc", extra_args=extra_args)\n # workaround for https://github.com/jgm/pandoc/issues/3068\n if "__" in asciidoc:\n asciidoc = re.sub(r"\b__([\w \n-]+)__([:,.\n\)])", r"_\1_\2", asciidoc)\n # urls / links:\n asciidoc = re.sub(r"\(__([\w\/-:\.]+)__\)", r"(_\1_)", asciidoc)\n\n return asciidoc\n\n\n# The mistune renderer is the default, because it's simple to depend on it\nmarkdown2html = markdown2html_mistune\n\n\ndef markdown2rst(source, extra_args=None):\n """\n Convert a markdown string to ReST via pandoc.\n\n This function will raise an error if pandoc is not installed.\n Any error messages generated by pandoc are printed to stderr.\n\n Parameters\n ----------\n source : string\n Input string, assumed to be valid markdown.\n\n Returns\n -------\n out : string\n Output as returned by pandoc.\n """\n return convert_pandoc(source, _MARKDOWN_FMT, "rst", extra_args=extra_args)\n | .venv\Lib\site-packages\nbconvert\filters\markdown.py | markdown.py | Python | 3,399 | 0.95 | 0.119658 | 0.093023 | python-kit | 832 | 2023-09-30T19:33:56.527904 | MIT | false | 1f19fbbd74e1aa00476473f653b9f927 |
"""Markdown filters with mistune\n\nUsed from markdown.py\n"""\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport base64\nimport mimetypes\nimport os\nfrom html import escape\nfrom typing import TYPE_CHECKING, Any, ClassVar, Dict, Iterable, Match, Optional, Protocol, Tuple\n\nimport bs4\nfrom pygments import highlight\nfrom pygments.formatters import HtmlFormatter\nfrom pygments.lexer import Lexer\nfrom pygments.lexers import get_lexer_by_name\nfrom pygments.util import ClassNotFound\n\nfrom nbconvert.filters.strings import add_anchor\n\nif TYPE_CHECKING:\n try:\n from mistune.plugins import Plugin\n except ImportError:\n\n class Plugin(Protocol): # type: ignore[no-redef]\n """Mistune plugin interface."""\n\n def __call__(self, markdown: "Markdown") -> None:\n """Apply the plugin on the markdown document."""\n ...\n\n\ntry: # for Mistune >= 3.0\n from mistune import ( # type:ignore[attr-defined]\n BlockParser,\n BlockState,\n HTMLRenderer,\n InlineParser,\n InlineState,\n Markdown,\n import_plugin,\n )\n\n MISTUNE_V3 = True\n MISTUNE_V3_ATX = "atx_heading" in BlockParser.SPECIFICATION\n\nexcept ImportError: # for Mistune >= 2.0\n import re\n\n from mistune import ( # type: ignore[attr-defined]\n PLUGINS,\n BlockParser,\n HTMLRenderer,\n InlineParser,\n Markdown,\n )\n\n MISTUNE_V3 = False\n MISTUNE_V3_ATX = False\n\n def import_plugin(name: str) -> "Plugin": # type: ignore[misc]\n """Simple implementation of Mistune V3's import_plugin for V2."""\n return PLUGINS[name] # type: ignore[no-any-return]\n\n\nclass InvalidNotebook(Exception):\n """An invalid notebook model."""\n\n\ndef _dotall(pattern: str) -> str:\n """Makes the '.' special character match any character inside the pattern, including a newline.\n\n This is implemented with the inline flag `(?s:...)` and is equivalent to using `re.DOTALL`.\n It is useful for LaTeX environments, where line breaks may be present.\n """\n return f"(?s:{pattern})"\n\n\nif MISTUNE_V3: # Parsers for Mistune >= 3.0.0\n\n class MathBlockParser(BlockParser):\n """This acts as a pass-through to the MathInlineParser. It is needed in\n order to avoid other block level rules splitting math sections apart.\n\n It works by matching each multiline math environment as a single paragraph,\n so that other rules don't think each section is its own paragraph. Inline\n is ignored here.\n """\n\n ATX_HEADING_WITHOUT_LEADING_SPACES = (\n r"^ {0,3}(?P<atx_1>#{1,6})(?!#+)(?P<atx_2>[ \t]*(.*?)?)$"\n if MISTUNE_V3_ATX\n else r"^ {0,3}(?P<axt_1>#{1,6})(?!#+)(?P<axt_2>[ \t]*(.*?)?)$"\n )\n\n MULTILINE_MATH = _dotall(\n # Display math mode, old TeX delimiter: $$ \sqrt{2} $$\n r"(?<!\\)[$]{2}.*?(?<!\\)[$]{2}"\n "|"\n # Display math mode, new LaTeX delimiter: \[ \sqrt{2} \]\n r"\\\\\[.*?\\\\\]"\n "|"\n # LaTeX environment: \begin{equation} \sqrt{2} \end{equation}\n r"\\begin\{(?P<math_env_name>[a-z]*\*?)\}.*?\\end\{(?P=math_env_name)\}"\n )\n\n SPECIFICATION = {\n **BlockParser.SPECIFICATION,\n (\n "atx_heading" if MISTUNE_V3_ATX else "axt_heading"\n ): ATX_HEADING_WITHOUT_LEADING_SPACES,\n "multiline_math": MULTILINE_MATH,\n }\n\n # Multiline math must be searched before other rules\n DEFAULT_RULES: ClassVar[Iterable[str]] = ("multiline_math", *BlockParser.DEFAULT_RULES) # type: ignore[assignment]\n\n def parse_multiline_math(self, m: Match[str], state: BlockState) -> int:\n """Send mutiline math as a single paragraph to MathInlineParser."""\n matched_text = m[0]\n state.add_paragraph(matched_text)\n return m.end()\n\n class MathInlineParser(InlineParser):\n r"""This interprets the content of LaTeX style math objects.\n\n In particular this grabs ``$$...$$``, ``\\[...\\]``, ``\\(...\\)``, ``$...$``,\n and ``\begin{foo}...\end{foo}`` styles for declaring mathematics. It strips\n delimiters from all these varieties, and extracts the type of environment\n in the last case (``foo`` in this example).\n """\n\n # Display math mode, using older TeX delimiter: $$ \pi $$\n BLOCK_MATH_TEX = _dotall(r"(?<!\\)\$\$(?P<math_block_tex>.*?)(?<!\\)\$\$")\n # Display math mode, using newer LaTeX delimiter: \[ \pi \]\n BLOCK_MATH_LATEX = _dotall(r"(?<!\\)\\\\\[(?P<math_block_latex>.*?)(?<!\\)\\\\\]")\n # Inline math mode, using older TeX delimiter: $ \pi $ (cannot be empty!)\n INLINE_MATH_TEX = _dotall(r"(?<![$\\])\$(?P<math_inline_tex>.+?)(?<![$\\])\$")\n # Inline math mode, using newer LaTeX delimiter: \( \pi \)\n INLINE_MATH_LATEX = _dotall(r"(?<!\\)\\\\\((?P<math_inline_latex>.*?)(?<!\\)\\\\\)")\n # LaTeX math environment: \begin{equation} \pi \end{equation}\n LATEX_ENVIRONMENT = _dotall(\n r"\\begin\{(?P<math_env_name>[a-z]*\*?)\}"\n r"(?P<math_env_body>.*?)"\n r"\\end\{(?P=math_env_name)\}"\n )\n\n SPECIFICATION = {\n **InlineParser.SPECIFICATION,\n "block_math_tex": BLOCK_MATH_TEX,\n "block_math_latex": BLOCK_MATH_LATEX,\n "inline_math_tex": INLINE_MATH_TEX,\n "inline_math_latex": INLINE_MATH_LATEX,\n "latex_environment": LATEX_ENVIRONMENT,\n }\n\n # Block math must be matched first, and all math must come before text\n DEFAULT_RULES: ClassVar[Iterable[str]] = (\n "block_math_tex",\n "block_math_latex",\n "inline_math_tex",\n "inline_math_latex",\n "latex_environment",\n *InlineParser.DEFAULT_RULES,\n ) # type: ignore[assignment]\n\n def parse_block_math_tex(self, m: Match[str], state: InlineState) -> int:\n """Parse older TeX-style display math."""\n body = m.group("math_block_tex")\n state.append_token({"type": "block_math", "raw": body})\n return m.end()\n\n def parse_block_math_latex(self, m: Match[str], state: InlineState) -> int:\n """Parse newer LaTeX-style display math."""\n body = m.group("math_block_latex")\n state.append_token({"type": "block_math", "raw": body})\n return m.end()\n\n def parse_inline_math_tex(self, m: Match[str], state: InlineState) -> int:\n """Parse older TeX-style inline math."""\n body = m.group("math_inline_tex")\n state.append_token({"type": "inline_math", "raw": body})\n return m.end()\n\n def parse_inline_math_latex(self, m: Match[str], state: InlineState) -> int:\n """Parse newer LaTeX-style inline math."""\n body = m.group("math_inline_latex")\n state.append_token({"type": "inline_math", "raw": body})\n return m.end()\n\n def parse_latex_environment(self, m: Match[str], state: InlineState) -> int:\n """Parse a latex environment."""\n attrs = {"name": m.group("math_env_name"), "body": m.group("math_env_body")}\n state.append_token({"type": "latex_environment", "attrs": attrs})\n return m.end()\n\nelse: # Parsers for Mistune >= 2.0.0 < 3.0.0\n\n class MathBlockParser(BlockParser): # type: ignore[no-redef]\n """This acts as a pass-through to the MathInlineParser. It is needed in\n order to avoid other block level rules splitting math sections apart.\n """\n\n MULTILINE_MATH = re.compile(\n # Display math mode, old TeX delimiter: $$ \sqrt{2} $$\n r"(?<!\\)[$]{2}.*?(?<!\\)[$]{2}|"\n # Display math mode, new LaTeX delimiter: \[ \sqrt{2} \]\n r"\\\\\[.*?\\\\\]|"\n # LaTeX environment: \begin{equation} \sqrt{2} \end{equation}\n r"\\begin\{([a-z]*\*?)\}.*?\\end\{\1\}",\n re.DOTALL,\n )\n\n # Regex for header that doesn't require space after '#'\n AXT_HEADING = re.compile(r" {0,3}(#{1,6})(?!#+)(?: *\n+|([^\n]*?)(?:\n+|\s+?#+\s*\n+))")\n\n # Multiline math must be searched before other rules\n RULE_NAMES = ("multiline_math", *BlockParser.RULE_NAMES) # type: ignore[attr-defined]\n\n def parse_multiline_math(self, m: Match[str], state: Any) -> Dict[str, str]:\n """Pass token through mutiline math."""\n return {"type": "multiline_math", "text": m.group(0)}\n\n class MathInlineParser(InlineParser): # type: ignore[no-redef]\n r"""This interprets the content of LaTeX style math objects.\n\n In particular this grabs ``$$...$$``, ``\\[...\\]``, ``\\(...\\)``, ``$...$``,\n and ``\begin{foo}...\end{foo}`` styles for declaring mathematics. It strips\n delimiters from all these varieties, and extracts the type of environment\n in the last case (``foo`` in this example).\n """\n\n # Display math mode, using older TeX delimiter: $$ \pi $$\n BLOCK_MATH_TEX = _dotall(r"(?<!\\)\$\$(.*?)(?<!\\)\$\$")\n # Display math mode, using newer LaTeX delimiter: \[ \pi \]\n BLOCK_MATH_LATEX = _dotall(r"(?<!\\)\\\\\[(.*?)(?<!\\)\\\\\]")\n # Inline math mode, using older TeX delimiter: $ \pi $ (cannot be empty!)\n INLINE_MATH_TEX = _dotall(r"(?<![$\\])\$(.+?)(?<![$\\])\$")\n # Inline math mode, using newer LaTeX delimiter: \( \pi \)\n INLINE_MATH_LATEX = _dotall(r"(?<!\\)\\\\\((.*?)(?<!\\)\\\\\)")\n # LaTeX math environment: \begin{equation} \pi \end{equation}\n LATEX_ENVIRONMENT = _dotall(r"\\begin\{([a-z]*\*?)\}(.*?)\\end\{\1\}")\n\n RULE_NAMES = (\n "block_math_tex",\n "block_math_latex",\n "inline_math_tex",\n "inline_math_latex",\n "latex_environment",\n *InlineParser.RULE_NAMES, # type: ignore[attr-defined]\n )\n\n def parse_block_math_tex(self, m: Match[str], state: Any) -> Tuple[str, str]:\n """Parse block text math."""\n # sometimes the Scanner keeps the final '$$', so we use the\n # full matched string and remove the math markers\n text = m.group(0)[2:-2]\n return "block_math", text\n\n def parse_block_math_latex(self, m: Match[str], state: Any) -> Tuple[str, str]:\n """Parse block latex math ."""\n text = m.group(1)\n return "block_math", text\n\n def parse_inline_math_tex(self, m: Match[str], state: Any) -> Tuple[str, str]:\n """Parse inline tex math."""\n text = m.group(1)\n return "inline_math", text\n\n def parse_inline_math_latex(self, m: Match[str], state: Any) -> Tuple[str, str]:\n """Parse inline latex math."""\n text = m.group(1)\n return "inline_math", text\n\n def parse_latex_environment(self, m: Match[str], state: Any) -> Tuple[str, str, str]:\n """Parse a latex environment."""\n name, text = m.group(1), m.group(2)\n return "latex_environment", name, text\n\n\nclass IPythonRenderer(HTMLRenderer):\n """An ipython html renderer."""\n\n def __init__(\n self,\n escape: bool = True,\n allow_harmful_protocols: bool = True,\n embed_images: bool = False,\n exclude_anchor_links: bool = False,\n anchor_link_text: str = "¶",\n path: str = "",\n attachments: Optional[Dict[str, Dict[str, str]]] = None,\n **lexer_options,\n ):\n """Initialize the renderer."""\n super().__init__(escape, allow_harmful_protocols)\n self.embed_images = embed_images\n self.exclude_anchor_links = exclude_anchor_links\n self.anchor_link_text = anchor_link_text\n self.path = path\n self.lexer_options = lexer_options\n if attachments is not None:\n self.attachments = attachments\n else:\n self.attachments = {}\n\n def block_code(self, code: str, info: Optional[str] = None) -> str:\n """Handle block code."""\n lang: Optional[str] = ""\n lexer: Optional[Lexer] = None\n\n if info:\n if info.startswith("mermaid"):\n return self.block_mermaidjs(code)\n\n try:\n if info.strip().split(None, 1):\n lang = info.strip().split(maxsplit=1)[0]\n lexer = get_lexer_by_name(lang, **self.lexer_options)\n except ClassNotFound:\n code = f"{lang}\n{code}"\n lang = None\n\n if not lang:\n return super().block_code(code, info=info)\n\n formatter = HtmlFormatter()\n return highlight(code, lexer, formatter)\n\n def block_mermaidjs(self, code: str) -> str:\n """Handle mermaid syntax."""\n return (\n """<div class="jp-Mermaid"><pre class="mermaid">\n"""\n f"""{code.strip()}"""\n """\n</pre></div>"""\n )\n\n def block_html(self, html: str) -> str:\n """Handle block html."""\n if self.embed_images:\n html = self._html_embed_images(html)\n\n return super().block_html(html)\n\n def inline_html(self, html: str) -> str:\n """Handle inline html."""\n if self.embed_images:\n html = self._html_embed_images(html)\n\n return super().inline_html(html)\n\n def heading(self, text: str, level: int, **attrs: Dict[str, Any]) -> str:\n """Handle a heading."""\n html = super().heading(text, level, **attrs)\n if self.exclude_anchor_links:\n return html\n return str(add_anchor(html, anchor_link_text=self.anchor_link_text))\n\n def escape_html(self, text: str) -> str:\n """Escape html content."""\n return escape(text, quote=False)\n\n def block_math(self, body: str) -> str:\n """Handle block math."""\n return f"$${self.escape_html(body)}$$"\n\n def multiline_math(self, text: str) -> str:\n """Handle mulitline math for older mistune versions."""\n return text\n\n def latex_environment(self, name: str, body: str) -> str:\n """Handle a latex environment."""\n name, body = self.escape_html(name), self.escape_html(body)\n return f"\\begin{{{name}}}{body}\\end{{{name}}}"\n\n def inline_math(self, body: str) -> str:\n """Handle inline math."""\n return f"${self.escape_html(body)}$"\n\n def image(self, text: str, url: str, title: Optional[str] = None) -> str:\n """Rendering a image with title and text.\n\n :param text: alt text of the image.\n :param url: source link of the image.\n :param title: title text of the image.\n\n :note: The parameters `text` and `url` are swapped in older versions\n of mistune.\n """\n if MISTUNE_V3:\n url = self._embed_image_or_attachment(url)\n else: # for mistune v2, the first argument is the URL\n text = self._embed_image_or_attachment(text)\n\n return super().image(text, url, title)\n\n def _embed_image_or_attachment(self, src: str) -> str:\n """Embed an image or attachment, depending on the configuration.\n If neither is possible, returns the original URL.\n """\n\n attachment_prefix = "attachment:"\n if src.startswith(attachment_prefix):\n name = src[len(attachment_prefix) :]\n\n if name not in self.attachments:\n msg = f"missing attachment: {name}"\n raise InvalidNotebook(msg)\n\n attachment = self.attachments[name]\n # we choose vector over raster, and lossless over lossy\n preferred_mime_types = ("image/svg+xml", "image/png", "image/jpeg")\n for mime_type in preferred_mime_types:\n if mime_type in attachment:\n return f"data:{mime_type};base64,{attachment[mime_type]}"\n # otherwise we choose the first mimetype we can find\n default_mime_type = next(iter(attachment.keys()))\n return f"data:{default_mime_type};base64,{attachment[default_mime_type]}"\n\n if self.embed_images:\n base64_url = self._src_to_base64(src)\n if base64_url is not None:\n return base64_url\n\n return src\n\n def _src_to_base64(self, src: str) -> Optional[str]:\n """Turn the source file into a base64 url.\n\n :param src: source link of the file.\n :return: the base64 url or None if the file was not found.\n """\n src_path = os.path.join(self.path, src)\n\n if not os.path.exists(src_path):\n return None\n\n with open(src_path, "rb") as fobj:\n mime_type, _ = mimetypes.guess_type(src_path)\n\n base64_data = base64.b64encode(fobj.read())\n base64_str = base64_data.replace(b"\n", b"").decode("ascii")\n\n return f"data:{mime_type};base64,{base64_str}"\n\n def _html_embed_images(self, html: str) -> str:\n parsed_html = bs4.BeautifulSoup(html, features="html.parser")\n imgs: bs4.ResultSet[bs4.Tag] = parsed_html.find_all("img")\n\n # Replace img tags's sources by base64 dataurls\n for img in imgs:\n src = img.attrs.get("src")\n if src is None:\n continue\n\n base64_url = self._src_to_base64(img.attrs["src"])\n if base64_url is not None:\n img.attrs["src"] = base64_url\n\n return str(parsed_html)\n\n\nclass MarkdownWithMath(Markdown):\n """Markdown text with math enabled."""\n\n DEFAULT_PLUGINS = (\n # "abbr", (see https://github.com/jupyter/nbconvert/pull/1853)\n # "footnotes",\n "strikethrough",\n "table",\n "url",\n "task_lists",\n "def_list",\n )\n\n def __init__(\n self,\n renderer: HTMLRenderer,\n block: Optional[BlockParser] = None,\n inline: Optional[InlineParser] = None,\n plugins: Optional[Iterable["Plugin"]] = None,\n ):\n """Initialize the parser."""\n if block is None:\n block = MathBlockParser()\n if inline is None:\n if MISTUNE_V3:\n inline = MathInlineParser(hard_wrap=False)\n else:\n inline = MathInlineParser(renderer, hard_wrap=False) # type: ignore[arg-type,misc]\n if plugins is None:\n plugins = (import_plugin(p) for p in self.DEFAULT_PLUGINS)\n\n super().__init__(renderer, block, inline, plugins)\n\n def render(self, source: str) -> str:\n """Render the HTML output for a Markdown source."""\n return str(super().__call__(source))\n\n\ndef markdown2html_mistune(source: str) -> str:\n """Convert a markdown string to HTML using mistune"""\n return MarkdownWithMath(renderer=IPythonRenderer(escape=False)).render(source)\n | .venv\Lib\site-packages\nbconvert\filters\markdown_mistune.py | markdown_mistune.py | Python | 18,978 | 0.95 | 0.171937 | 0.083744 | node-utils | 1 | 2025-05-21T09:45:00.225241 | Apache-2.0 | false | 77fea2aacf026aa5c480abf280068c27 |
"""filters for metadata"""\n\n\ndef get_metadata(output, key, mimetype=None):\n """Resolve an output metadata key\n\n If mimetype given, resolve at mimetype level first,\n then fallback to top-level.\n Otherwise, just resolve at top-level.\n Returns None if no data found.\n """\n md = output.get("metadata") or {}\n if mimetype and mimetype in md:\n value = md[mimetype].get(key)\n if value is not None:\n return value\n return md.get(key)\n | .venv\Lib\site-packages\nbconvert\filters\metadata.py | metadata.py | Python | 477 | 0.85 | 0.294118 | 0 | node-utils | 972 | 2024-01-07T05:31:00.799258 | BSD-3-Clause | false | e6b902334dfc4111b690e6db690d7f39 |
"""\nConvert between any two formats using pandoc,\nand related filters\n"""\n\nimport os\n\nfrom pandocfilters import Image, applyJSONFilters # type:ignore[import-untyped]\n\nfrom nbconvert.utils.base import NbConvertBase\nfrom nbconvert.utils.pandoc import pandoc\n\n__all__ = ["ConvertExplicitlyRelativePaths", "convert_pandoc"]\n\n\ndef convert_pandoc(source, from_format, to_format, extra_args=None):\n """Convert between any two formats using pandoc.\n\n This function will raise an error if pandoc is not installed.\n Any error messages generated by pandoc are printed to stderr.\n\n Parameters\n ----------\n source : string\n Input string, assumed to be valid in from_format.\n from_format : string\n Pandoc format of source.\n to_format : string\n Pandoc format for output.\n\n Returns\n -------\n out : string\n Output as returned by pandoc.\n """\n return pandoc(source, from_format, to_format, extra_args=extra_args)\n\n\n# When converting to pdf, explicitly relative references\n# like "./" and "../" doesn't work with TEXINPUTS.\n# So we need to convert them to absolute paths.\n# See https://github.com/jupyter/nbconvert/issues/1998\nclass ConvertExplicitlyRelativePaths(NbConvertBase):\n """A converter that handles relative path references."""\n\n def __init__(self, texinputs=None, **kwargs):\n """Initialize the converter."""\n # texinputs should be the directory of the notebook file\n self.nb_dir = os.path.abspath(texinputs) if texinputs else ""\n self.ancestor_dirs = self.nb_dir.split("/")\n super().__init__(**kwargs)\n\n def __call__(self, source):\n """Invoke the converter."""\n # If this is not set for some reason, we can't do anything,\n if self.nb_dir:\n return applyJSONFilters([self.action], source)\n return source\n\n def action(self, key, value, frmt, meta):\n """Perform the action."""\n # Convert explicitly relative paths:\n # ./path -> path (This should be visible to the latex engine since TEXINPUTS already has .)\n # ../path -> /abs_path\n # assuming all relative references are at the start of a given path\n if key == "Image":\n # Image seems to have this composition, according to https://github.com/jgm/pandoc-types\n attr, caption, [filename, typedef] = value\n\n if filename[:2] == "./":\n filename = filename[2:]\n elif filename[:3] == "../":\n n_up = 0\n while filename[:3] == "../":\n n_up += 1\n filename = filename[3:]\n ancestors = "/".join(self.ancestor_dirs[:-n_up]) + "/"\n filename = ancestors + filename\n return Image(attr, caption, [filename, typedef])\n # If not image, return "no change"\n return None\n | .venv\Lib\site-packages\nbconvert\filters\pandoc.py | pandoc.py | Python | 2,867 | 0.95 | 0.17284 | 0.181818 | vue-tools | 651 | 2024-08-02T04:29:58.455537 | BSD-3-Clause | false | 6291acfe45d0d61777757372abf6bba0 |
"""String filters.\n\nContains a collection of useful string manipulation filters for use in Jinja\ntemplates.\n"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport base64\nimport os\nimport re\nimport textwrap\nimport warnings\nfrom urllib.parse import quote\nfrom xml.etree.ElementTree import Element\n\nimport bleach\n\n# defusedxml does safe(r) parsing of untrusted XML data\nfrom defusedxml import ElementTree # type:ignore[import-untyped]\n\nfrom nbconvert.preprocessors.sanitize import _get_default_css_sanitizer\n\n__all__ = [\n "wrap_text",\n "html2text",\n "clean_html",\n "add_anchor",\n "strip_dollars",\n "strip_files_prefix",\n "comment_lines",\n "get_lines",\n "ipython2python",\n "posix_path",\n "path2url",\n "add_prompts",\n "ascii_only",\n "prevent_list_blocks",\n "strip_trailing_newline",\n "text_base64",\n]\n\n\ndef wrap_text(text, width=100):\n """\n Intelligently wrap text.\n Wrap text without breaking words if possible.\n\n Parameters\n ----------\n text : str\n Text to wrap.\n width : int, optional\n Number of characters to wrap to, default 100.\n """\n\n split_text = text.split("\n")\n wrp = map(lambda x: textwrap.wrap(x, width), split_text) # noqa: C417\n wrpd = map("\n".join, wrp)\n return "\n".join(wrpd)\n\n\ndef html2text(element):\n """extract inner text from html\n\n Analog of jQuery's $(element).text()\n """\n if isinstance(element, (str,)):\n try:\n element = ElementTree.fromstring(element)\n except Exception:\n # failed to parse, just return it unmodified\n return element\n\n text = element.text or ""\n for child in element:\n text += html2text(child)\n text += element.tail or ""\n return text\n\n\ndef clean_html(element):\n """Clean an html element."""\n element = element.decode() if isinstance(element, bytes) else str(element)\n kwargs = {}\n css_sanitizer = _get_default_css_sanitizer()\n if css_sanitizer:\n kwargs["css_sanitizer"] = css_sanitizer\n return bleach.clean(\n element,\n tags=[*bleach.ALLOWED_TAGS, "div", "pre", "code", "span", "table", "tr", "td"],\n attributes={\n **bleach.ALLOWED_ATTRIBUTES,\n "*": ["class", "id"],\n },\n **kwargs,\n )\n\n\ndef _convert_header_id(header_contents):\n """Convert header contents to valid id value. Takes string as input, returns string.\n\n Note: this may be subject to change in the case of changes to how we wish to generate ids.\n\n For use on markdown headings.\n """\n # Valid IDs need to be non-empty and contain no space characters, but are otherwise arbitrary.\n # However, these IDs are also used in URL fragments, which are more restrictive, so we URL\n # encode any characters that are not valid in URL fragments.\n return quote(header_contents.replace(" ", "-"), safe="?/:@!$&'()*+,;=")\n\n\ndef add_anchor(html, anchor_link_text="¶"):\n """Add an id and an anchor-link to an html header\n\n For use on markdown headings\n """\n try:\n h = ElementTree.fromstring(html)\n except Exception:\n # failed to parse, just return it unmodified\n return html\n link = _convert_header_id(html2text(h))\n h.set("id", link)\n a = Element("a", {"class": "anchor-link", "href": "#" + link})\n try:\n # Test if the anchor link text is HTML (e.g. an image)\n a.append(ElementTree.fromstring(anchor_link_text))\n except Exception:\n # If we fail to parse, assume we've just got regular text\n a.text = anchor_link_text\n h.append(a)\n\n return ElementTree.tostring(h).decode(encoding="utf-8")\n\n\ndef add_prompts(code, first=">>> ", cont="... "):\n """Add prompts to code snippets"""\n new_code = []\n code_list = code.split("\n")\n new_code.append(first + code_list[0])\n for line in code_list[1:]:\n new_code.append(cont + line)\n return "\n".join(new_code)\n\n\ndef strip_dollars(text):\n """\n Remove all dollar symbols from text\n\n Parameters\n ----------\n text : str\n Text to remove dollars from\n """\n\n return text.strip("$")\n\n\nfiles_url_pattern = re.compile(r'(src|href)\=([\'"]?)/?files/')\nmarkdown_url_pattern = re.compile(r"(!?)\[(?P<caption>.*?)\]\(/?files/(?P<location>.*?)\)")\n\n\ndef strip_files_prefix(text):\n """\n Fix all fake URLs that start with ``files/``, stripping out the ``files/`` prefix.\n Applies to both urls (for html) and relative paths (for markdown paths).\n\n Parameters\n ----------\n text : str\n Text in which to replace 'src="files/real...' with 'src="real...'\n """\n cleaned_text = files_url_pattern.sub(r"\1=\2", text)\n cleaned_text = markdown_url_pattern.sub(r"\1[\2](\3)", cleaned_text)\n return cleaned_text # noqa: RET504\n\n\ndef comment_lines(text, prefix="# "):\n """\n Build a Python comment line from input text.\n\n Parameters\n ----------\n text : str\n Text to comment out.\n prefix : str\n Character to append to the start of each line.\n """\n\n # Replace line breaks with line breaks and comment symbols.\n # Also add a comment symbol at the beginning to comment out\n # the first line.\n return prefix + ("\n" + prefix).join(text.split("\n"))\n\n\ndef get_lines(text, start=None, end=None):\n """\n Split the input text into separate lines and then return the\n lines that the caller is interested in.\n\n Parameters\n ----------\n text : str\n Text to parse lines from.\n start : int, optional\n First line to grab from.\n end : int, optional\n Last line to grab from.\n """\n\n # Split the input into lines.\n lines = text.split("\n")\n\n # Return the right lines.\n return "\n".join(lines[start:end]) # re-join\n\n\ndef ipython2python(code):\n """Transform IPython syntax to pure Python syntax\n\n Parameters\n ----------\n code : str\n IPython code, to be transformed to pure Python\n """\n try:\n from IPython.core.inputtransformer2 import TransformerManager\n except ImportError:\n warnings.warn(\n "IPython is needed to transform IPython syntax to pure Python."\n " Install ipython if you need this functionality.",\n stacklevel=2,\n )\n return code\n else:\n isp = TransformerManager()\n return isp.transform_cell(code)\n\n\ndef posix_path(path):\n """Turn a path into posix-style path/to/etc\n\n Mainly for use in latex on Windows,\n where native Windows paths are not allowed.\n """\n if os.path.sep != "/":\n return path.replace(os.path.sep, "/")\n return path\n\n\ndef path2url(path):\n """Turn a file path into a URL"""\n parts = path.split(os.path.sep)\n return "/".join(quote(part) for part in parts)\n\n\ndef ascii_only(s):\n """ensure a string is ascii"""\n return s.encode("ascii", "replace").decode("ascii")\n\n\ndef prevent_list_blocks(s):\n """\n Prevent presence of enumerate or itemize blocks in latex headings cells\n """\n out = re.sub(r"(^\s*\d*)\.", r"\1\.", s)\n out = re.sub(r"(^\s*)\-", r"\1\-", out)\n out = re.sub(r"(^\s*)\+", r"\1\+", out)\n out = re.sub(r"(^\s*)\*", r"\1\*", out)\n return out # noqa: RET504\n\n\ndef strip_trailing_newline(text):\n """\n Strips a newline from the end of text.\n """\n if text.endswith("\n"):\n text = text[:-1]\n return text\n\n\ndef text_base64(text):\n """\n Encode base64 text\n """\n return base64.b64encode(text.encode()).decode()\n | .venv\Lib\site-packages\nbconvert\filters\strings.py | strings.py | Python | 7,536 | 0.95 | 0.131944 | 0.07489 | react-lib | 148 | 2023-11-02T08:04:35.196779 | GPL-3.0 | false | e4e369ae7d299f8e49c3ae6be77b50bb |
"""Filter used to select the first preferred output format available,\nexcluding interactive widget format if the widget state is not available.\n\nThe filter contained in the file allows the converter templates to select\nthe output format that is most valuable to the active export format. The\nvalue of the different formats is set via\nNbConvertBase.display_data_priority\n"""\n# -----------------------------------------------------------------------------\n# Copyright (c) 2013, the IPython Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# -----------------------------------------------------------------------------\n\n# -----------------------------------------------------------------------------\n# Classes and functions\n# -----------------------------------------------------------------------------\n\nimport os\nfrom warnings import warn\n\nfrom nbconvert.utils.base import NbConvertBase\n\n__all__ = ["WidgetsDataTypeFilter"]\n\n\nWIDGET_VIEW_MIMETYPE = "application/vnd.jupyter.widget-view+json"\nWIDGET_STATE_MIMETYPE = "application/vnd.jupyter.widget-state+json"\n\n\nclass WidgetsDataTypeFilter(NbConvertBase):\n """Returns the preferred display format, excluding the widget output if\n there is no widget state available"""\n\n def __init__(self, notebook_metadata=None, resources=None, **kwargs):\n """Initialize the filter."""\n self.metadata = notebook_metadata\n self.notebook_path = ""\n if resources is not None:\n name = resources.get("metadata", {}).get("name", "")\n path = resources.get("metadata", {}).get("path", "")\n self.notebook_path = os.path.join(path, name)\n\n super().__init__(**kwargs)\n\n def __call__(self, output):\n """Return the first available format in the priority.\n\n Produces a UserWarning if no compatible mimetype is found.\n\n `output` is dict with structure {mimetype-of-element: value-of-element}\n\n """\n metadata = self.metadata.get(self.notebook_path, {})\n widgets_state = (\n metadata["widgets"][WIDGET_STATE_MIMETYPE]["state"]\n if metadata.get("widgets") is not None\n else {}\n )\n for fmt in self.display_data_priority:\n if fmt in output:\n # If there is no widget state available, we skip this mimetype\n if (\n fmt == WIDGET_VIEW_MIMETYPE\n and output[WIDGET_VIEW_MIMETYPE]["model_id"] not in widgets_state\n ):\n continue\n\n return [fmt]\n warn(\n f"Your element with mimetype(s) {output.keys()} is not able to be represented.",\n stacklevel=2,\n )\n\n return []\n | .venv\Lib\site-packages\nbconvert\filters\widgetsdatatypefilter.py | widgetsdatatypefilter.py | Python | 2,820 | 0.95 | 0.142857 | 0.183333 | node-utils | 255 | 2023-09-09T05:00:44.254231 | GPL-3.0 | false | 32a8d0478c8e595edc46fb61394c3856 |
from nbconvert.utils.text import indent\n\nfrom .ansi import ansi2html, ansi2latex, strip_ansi\nfrom .citation import citation2latex\nfrom .datatypefilter import DataTypeFilter\nfrom .highlight import Highlight2HTML, Highlight2Latex\nfrom .latex import escape_latex\nfrom .markdown import (\n markdown2asciidoc,\n markdown2html,\n markdown2html_mistune,\n markdown2html_pandoc,\n markdown2latex,\n markdown2rst,\n)\nfrom .metadata import get_metadata\nfrom .pandoc import ConvertExplicitlyRelativePaths, convert_pandoc\nfrom .strings import (\n add_anchor,\n add_prompts,\n ascii_only,\n clean_html,\n comment_lines,\n get_lines,\n html2text,\n ipython2python,\n path2url,\n posix_path,\n prevent_list_blocks,\n strip_dollars,\n strip_files_prefix,\n strip_trailing_newline,\n text_base64,\n wrap_text,\n)\n\n__all__ = [\n "indent",\n "ansi2html",\n "ansi2latex",\n "strip_ansi",\n "citation2latex",\n "DataTypeFilter",\n "Highlight2HTML",\n "Highlight2Latex",\n "escape_latex",\n "markdown2html",\n "markdown2html_pandoc",\n "markdown2html_mistune",\n "markdown2latex",\n "markdown2rst",\n "markdown2asciidoc",\n "get_metadata",\n "convert_pandoc",\n "ConvertExplicitlyRelativePaths",\n "wrap_text",\n "html2text",\n "clean_html",\n "add_anchor",\n "strip_dollars",\n "strip_files_prefix",\n "comment_lines",\n "get_lines",\n "ipython2python",\n "posix_path",\n "path2url",\n "add_prompts",\n "ascii_only",\n "prevent_list_blocks",\n "strip_trailing_newline",\n "text_base64",\n]\n | .venv\Lib\site-packages\nbconvert\filters\__init__.py | __init__.py | Python | 1,578 | 0.85 | 0 | 0 | node-utils | 203 | 2024-12-22T20:50:19.359075 | Apache-2.0 | false | ac48ef749f5a2c21a42a356ad86057ec |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\ansi.cpython-313.pyc | ansi.cpython-313.pyc | Other | 8,928 | 0.95 | 0.038217 | 0 | awesome-app | 265 | 2023-08-14T06:39:15.563830 | Apache-2.0 | false | 502d512ebb567b27483e59b349c51269 |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\citation.cpython-313.pyc | citation.cpython-313.pyc | Other | 3,943 | 0.8 | 0.041667 | 0 | react-lib | 832 | 2024-11-28T01:26:20.778555 | BSD-3-Clause | false | fb217424e6f24dd03205415f92b22549 |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\datatypefilter.cpython-313.pyc | datatypefilter.cpython-313.pyc | Other | 1,552 | 0.7 | 0.041667 | 0 | python-kit | 900 | 2025-01-06T14:32:06.839859 | MIT | false | 92f82534aad8cd80f313da2067caa476 |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\filter_links.cpython-313.pyc | filter_links.cpython-313.pyc | Other | 1,945 | 0.8 | 0.037037 | 0 | python-kit | 270 | 2024-12-19T04:20:18.498841 | Apache-2.0 | false | ce9a9d993c884013173d7cac528aefa5 |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\highlight.cpython-313.pyc | highlight.cpython-313.pyc | Other | 6,598 | 0.95 | 0.034783 | 0 | react-lib | 458 | 2025-07-06T05:31:08.945657 | Apache-2.0 | false | c5d27ffbcb04501a8956b95044f72c98 |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\latex.cpython-313.pyc | latex.cpython-313.pyc | Other | 1,329 | 0.8 | 0.035714 | 0 | react-lib | 887 | 2025-02-17T02:56:03.171741 | MIT | false | ca82c7642e69a588cc1a91d3d3b22277 |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\markdown.cpython-313.pyc | markdown.cpython-313.pyc | Other | 3,372 | 0.95 | 0.078125 | 0 | node-utils | 410 | 2025-07-02T13:46:19.543698 | BSD-3-Clause | false | f0f4ffff767cfc3cd2c5230703651f82 |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\markdown_mistune.cpython-313.pyc | markdown_mistune.cpython-313.pyc | Other | 21,702 | 0.95 | 0.035242 | 0 | vue-tools | 346 | 2024-09-13T21:50:40.931060 | MIT | false | d560fc9dd44edaaaf596cb437ce59a82 |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\metadata.cpython-313.pyc | metadata.cpython-313.pyc | Other | 795 | 0.8 | 0.153846 | 0 | node-utils | 307 | 2024-04-03T22:16:19.204443 | BSD-3-Clause | false | 13c133131bb6c6c52d35bad22be4d5c6 |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\pandoc.cpython-313.pyc | pandoc.cpython-313.pyc | Other | 3,043 | 0.95 | 0.075 | 0 | react-lib | 874 | 2024-11-15T21:23:44.205249 | GPL-3.0 | false | a79c158fd0a59edf3caf08c0adfcf803 |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\strings.cpython-313.pyc | strings.cpython-313.pyc | Other | 9,894 | 0.95 | 0.04321 | 0 | react-lib | 981 | 2025-01-17T11:46:26.322837 | GPL-3.0 | false | d047cf9b50fa32939fdce5db2abdf2cb |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\widgetsdatatypefilter.cpython-313.pyc | widgetsdatatypefilter.cpython-313.pyc | Other | 3,007 | 0.8 | 0.071429 | 0.027778 | awesome-app | 132 | 2024-12-01T00:09:59.512068 | GPL-3.0 | false | 9476d6317e630ce898a62d8b88a540c7 |
\n\n | .venv\Lib\site-packages\nbconvert\filters\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 1,495 | 0.8 | 0 | 0 | react-lib | 336 | 2023-11-18T07:01:12.035579 | BSD-3-Clause | false | c1b5ddec8669872afc8129c38322dd61 |
"""\nBasic post processor\n"""\n# -----------------------------------------------------------------------------\n# Copyright (c) 2013, the IPython Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# -----------------------------------------------------------------------------\n\n# -----------------------------------------------------------------------------\n# Imports\n# -----------------------------------------------------------------------------\n\nfrom nbconvert.utils.base import NbConvertBase\n\n\n# -----------------------------------------------------------------------------\n# Classes\n# -----------------------------------------------------------------------------\nclass PostProcessorBase(NbConvertBase):\n """The base class for post processors."""\n\n def __call__(self, input_):\n """\n See def postprocess() ...\n """\n self.postprocess(input_)\n\n def postprocess(self, input_):\n """\n Post-process output from a writer.\n """\n msg = "postprocess"\n raise NotImplementedError(msg)\n | .venv\Lib\site-packages\nbconvert\postprocessors\base.py | base.py | Python | 1,154 | 0.95 | 0.166667 | 0.433333 | awesome-app | 990 | 2024-11-04T09:41:28.158834 | Apache-2.0 | false | 11568c8e3754aa326587ed46f39daff7 |
"""PostProcessor for serving reveal.js HTML slideshows."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport os\nimport threading\nimport typing as t\nimport webbrowser\n\nfrom tornado import gen, httpserver, ioloop, log, web\nfrom tornado.httpclient import AsyncHTTPClient\nfrom traitlets import Bool, Int, Unicode\n\nfrom .base import PostProcessorBase\n\n\nclass ProxyHandler(web.RequestHandler):\n """handler the proxies requests from a local prefix to a CDN"""\n\n @gen.coroutine\n def get(self, prefix, url):\n """proxy a request to a CDN"""\n proxy_url = "/".join([self.settings["cdn"], url])\n client = self.settings["client"]\n response = yield client.fetch(proxy_url)\n\n for header in ["Content-Type", "Cache-Control", "Date", "Last-Modified", "Expires"]:\n if header in response.headers:\n self.set_header(header, response.headers[header])\n self.finish(response.body)\n\n\nclass ServePostProcessor(PostProcessorBase):\n """Post processor designed to serve files\n\n Proxies reveal.js requests to a CDN if no local reveal.js is present\n """\n\n open_in_browser = Bool(True, help="""Should the browser be opened automatically?""").tag(\n config=True\n )\n\n browser = Unicode(\n "",\n help="""Specify what browser should be used to open slides. See\n https://docs.python.org/3/library/webbrowser.html#webbrowser.register\n to see how keys are mapped to browser executables. If\n not specified, the default browser will be determined\n by the `webbrowser`\n standard library module, which allows setting of the BROWSER\n environment variable to override it.\n """,\n ).tag(config=True)\n\n reveal_cdn = Unicode(\n "https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.5.0", help="""URL for reveal.js CDN."""\n ).tag(config=True)\n reveal_prefix = Unicode("reveal.js", help="URL prefix for reveal.js").tag(config=True)\n ip = Unicode("127.0.0.1", help="The IP address to listen on.").tag(config=True)\n port = Int(8000, help="port for the server to listen on.").tag(config=True)\n\n def postprocess(self, input):\n """Serve the build directory with a webserver."""\n dirname, filename = os.path.split(input)\n handlers: list[tuple[t.Any, ...]] = [\n (r"/(.+)", web.StaticFileHandler, {"path": dirname}),\n (r"/", web.RedirectHandler, {"url": "/%s" % filename}),\n ]\n\n if "://" in self.reveal_prefix or self.reveal_prefix.startswith("//"):\n # reveal specifically from CDN, nothing to do\n pass\n elif os.path.isdir(os.path.join(dirname, self.reveal_prefix)):\n # reveal prefix exists\n self.log.info("Serving local %s", self.reveal_prefix)\n else:\n self.log.info("Redirecting %s requests to %s", self.reveal_prefix, self.reveal_cdn)\n handlers.insert(0, (r"/(%s)/(.*)" % self.reveal_prefix, ProxyHandler))\n\n app = web.Application(\n handlers, # type:ignore[arg-type]\n cdn=self.reveal_cdn,\n client=AsyncHTTPClient(),\n )\n\n # hook up tornado logging to our logger\n log.app_log = self.log\n\n http_server = httpserver.HTTPServer(app)\n http_server.listen(self.port, address=self.ip)\n url = "http://%s:%i/%s" % (self.ip, self.port, filename)\n print("Serving your slides at %s" % url)\n print("Use Control-C to stop this server")\n if self.open_in_browser:\n try:\n browser = webbrowser.get(self.browser or None)\n b = lambda: browser.open(url, new=2) # noqa: E731\n threading.Thread(target=b).start()\n except webbrowser.Error as e:\n self.log.warning("No web browser found: %s.", e)\n browser = None\n\n try:\n ioloop.IOLoop.instance().start()\n except KeyboardInterrupt:\n print("\nInterrupted")\n\n\ndef main(path):\n """allow running this module to serve the slides"""\n server = ServePostProcessor()\n server(path)\n\n\nif __name__ == "__main__":\n import sys\n\n main(sys.argv[1])\n | .venv\Lib\site-packages\nbconvert\postprocessors\serve.py | serve.py | Python | 4,366 | 0.95 | 0.141667 | 0.052632 | python-kit | 105 | 2024-05-19T01:47:45.087485 | BSD-3-Clause | false | 1f9641696bd084541f676ac324c4e63b |
from .base import PostProcessorBase\n\n# protect against unavailable tornado\ntry:\n from .serve import ServePostProcessor\nexcept ImportError:\n ServePostProcessor = None # type:ignore[misc,assignment]\n\n__all__ = ["PostProcessorBase", "ServePostProcessor"]\n | .venv\Lib\site-packages\nbconvert\postprocessors\__init__.py | __init__.py | Python | 259 | 0.95 | 0.111111 | 0.142857 | react-lib | 255 | 2023-07-29T17:42:38.219364 | BSD-3-Clause | false | de62db1c54999591ce08ad0b2dfd1e62 |
\n\n | .venv\Lib\site-packages\nbconvert\postprocessors\__pycache__\base.cpython-313.pyc | base.cpython-313.pyc | Other | 1,053 | 0.95 | 0.230769 | 0 | node-utils | 177 | 2024-01-03T18:47:29.704117 | MIT | false | 0f6bdf71b930584a0ef936461a7edfda |
\n\n | .venv\Lib\site-packages\nbconvert\postprocessors\__pycache__\serve.cpython-313.pyc | serve.cpython-313.pyc | Other | 6,863 | 0.8 | 0.065789 | 0 | python-kit | 236 | 2023-07-29T22:08:36.127951 | BSD-3-Clause | false | 6d7d2468bbbf77eec18440de524df907 |
\n\n | .venv\Lib\site-packages\nbconvert\postprocessors\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 420 | 0.8 | 0 | 0 | python-kit | 918 | 2024-12-08T16:03:31.121304 | GPL-3.0 | false | 93fa3f4e9aced51cf0ddd6eb4640055f |
"""Base class for preprocessors"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import Bool\n\nfrom nbconvert.utils.base import NbConvertBase\n\n\nclass Preprocessor(NbConvertBase):\n """A configurable preprocessor\n\n Inherit from this class if you wish to have configurability for your\n preprocessor.\n\n Any configurable traitlets this class exposed will be configurable in\n profiles using c.SubClassName.attribute = value\n\n You can overwrite `preprocess_cell()` to apply a transformation\n independently on each cell or `preprocess()` if you prefer your own\n logic. See corresponding docstring for information.\n\n Disabled by default and can be enabled via the config by\n 'c.YourPreprocessorName.enabled = True'\n """\n\n enabled = Bool(False).tag(config=True)\n\n def __init__(self, **kw):\n """\n Public constructor\n\n Parameters\n ----------\n config : Config\n Configuration file structure\n `**kw`\n Additional keyword arguments passed to parent\n """\n\n super().__init__(**kw)\n\n def __call__(self, nb, resources):\n """Apply the preprocessor."""\n if self.enabled:\n self.log.debug("Applying preprocessor: %s", self.__class__.__name__)\n return self.preprocess(nb, resources)\n return nb, resources\n\n def preprocess(self, nb, resources):\n """\n Preprocessing to apply on each notebook.\n\n Must return modified nb, resources.\n\n If you wish to apply your preprocessing to each cell, you might want\n to override preprocess_cell method instead.\n\n Parameters\n ----------\n nb : NotebookNode\n Notebook being converted\n resources : dictionary\n Additional resources used in the conversion process. Allows\n preprocessors to pass variables into the Jinja engine.\n """\n for index, cell in enumerate(nb.cells):\n nb.cells[index], resources = self.preprocess_cell(cell, resources, index)\n return nb, resources\n\n def preprocess_cell(self, cell, resources, index):\n """\n Override if you want to apply some preprocessing to each cell.\n Must return modified cell and resource dictionary.\n\n Parameters\n ----------\n cell : NotebookNode cell\n Notebook cell being processed\n resources : dictionary\n Additional resources used in the conversion process. Allows\n preprocessors to pass variables into the Jinja engine.\n index : int\n Index of the cell being processed\n """\n msg = "should be implemented by subclass"\n raise NotImplementedError(msg)\n | .venv\Lib\site-packages\nbconvert\preprocessors\base.py | base.py | Python | 2,793 | 0.95 | 0.181818 | 0.029412 | vue-tools | 895 | 2023-12-14T21:03:53.715623 | MIT | false | f9a595e5756d080b152d136f2088617b |
"""Module containing a preprocessor that removes metadata from code cells"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import Bool, Set\n\nfrom .base import Preprocessor\n\n\nclass ClearMetadataPreprocessor(Preprocessor):\n """\n Removes all the metadata from all code cells in a notebook.\n """\n\n clear_cell_metadata = Bool(\n True,\n help=("Flag to choose if cell metadata is to be cleared in addition to notebook metadata."),\n ).tag(config=True)\n clear_notebook_metadata = Bool(\n True,\n help=("Flag to choose if notebook metadata is to be cleared in addition to cell metadata."),\n ).tag(config=True)\n preserve_nb_metadata_mask = Set(\n [("language_info", "name")],\n help=(\n "Indicates the key paths to preserve when deleting metadata "\n "across both cells and notebook metadata fields. Tuples of "\n "keys can be passed to preserved specific nested values"\n ),\n ).tag(config=True)\n preserve_cell_metadata_mask = Set(\n help=(\n "Indicates the key paths to preserve when deleting metadata "\n "across both cells and notebook metadata fields. Tuples of "\n "keys can be passed to preserved specific nested values"\n )\n ).tag(config=True)\n\n def current_key(self, mask_key):\n """Get the current key for a mask key."""\n if isinstance(mask_key, str):\n return mask_key\n if len(mask_key) == 0:\n # Safeguard\n return None\n return mask_key[0]\n\n def current_mask(self, mask):\n """Get the current mask for a mask."""\n return {self.current_key(k) for k in mask if self.current_key(k) is not None}\n\n def nested_masks(self, mask):\n """Get the nested masks for a mask."""\n return {\n self.current_key(k[0]): k[1:]\n for k in mask\n if k and not isinstance(k, str) and len(k) > 1\n }\n\n def nested_filter(self, items, mask):\n """Get the nested filter for items given a mask."""\n keep_current = self.current_mask(mask)\n keep_nested_lookup = self.nested_masks(mask)\n for k, v in items:\n keep_nested = keep_nested_lookup.get(k)\n if k in keep_current:\n if keep_nested is not None:\n if isinstance(v, dict):\n yield k, dict(self.nested_filter(v.items(), keep_nested))\n else:\n yield k, v\n\n def preprocess_cell(self, cell, resources, cell_index):\n """\n All the code cells are returned with an empty metadata field.\n """\n if self.clear_cell_metadata and cell.cell_type == "code": # noqa: SIM102\n # Remove metadata\n if "metadata" in cell:\n cell.metadata = dict(\n self.nested_filter(cell.metadata.items(), self.preserve_cell_metadata_mask)\n )\n return cell, resources\n\n def preprocess(self, nb, resources):\n """\n Preprocessing to apply on each notebook.\n\n Must return modified nb, resources.\n\n Parameters\n ----------\n nb : NotebookNode\n Notebook being converted\n resources : dictionary\n Additional resources used in the conversion process. Allows\n preprocessors to pass variables into the Jinja engine.\n """\n nb, resources = super().preprocess(nb, resources)\n if self.clear_notebook_metadata and "metadata" in nb:\n nb.metadata = dict(\n self.nested_filter(nb.metadata.items(), self.preserve_nb_metadata_mask)\n )\n return nb, resources\n | .venv\Lib\site-packages\nbconvert\preprocessors\clearmetadata.py | clearmetadata.py | Python | 3,764 | 0.95 | 0.247619 | 0.043956 | vue-tools | 955 | 2025-04-09T19:49:26.581728 | GPL-3.0 | false | d818a638f61a173b85af0b83b415e683 |
"""Module containing a preprocessor that removes the outputs from code cells"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import Set\n\nfrom .base import Preprocessor\n\n\nclass ClearOutputPreprocessor(Preprocessor):\n """\n Removes the output from all code cells in a notebook.\n """\n\n remove_metadata_fields = Set({"collapsed", "scrolled"}).tag(config=True)\n\n def preprocess_cell(self, cell, resources, cell_index):\n """\n Apply a transformation on each cell. See base.py for details.\n """\n if cell.cell_type == "code":\n cell.outputs = []\n cell.execution_count = None\n # Remove metadata associated with output\n if "metadata" in cell:\n for field in self.remove_metadata_fields:\n cell.metadata.pop(field, None)\n return cell, resources\n | .venv\Lib\site-packages\nbconvert\preprocessors\clearoutput.py | clearoutput.py | Python | 930 | 0.95 | 0.206897 | 0.136364 | awesome-app | 815 | 2024-05-10T13:28:25.007318 | MIT | false | fbfb94313fe3314217eddbd941188fd6 |
"""Preprocessor for merging consecutive stream outputs for easier handling."""\n\nimport re\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom nbconvert.preprocessors import Preprocessor\n\nCR_PAT = re.compile(r".*\r(?=[^\n])")\n\n\nclass CoalesceStreamsPreprocessor(Preprocessor):\n """\n Merge consecutive sequences of stream output into single stream\n to prevent extra newlines inserted at flush calls\n """\n\n def preprocess_cell(self, cell, resources, cell_index):\n """\n Apply a transformation on each cell. See base.py for details.\n """\n outputs = cell.get("outputs", [])\n if not outputs:\n return cell, resources\n\n last = outputs[0]\n new_outputs = [last]\n for output in outputs[1:]:\n if (\n output.output_type == "stream"\n and last.output_type == "stream"\n and last.name == output.name\n ):\n last.text += output.text\n else:\n new_outputs.append(output)\n last = output\n\n # process \r characters\n for output in new_outputs:\n if output.output_type == "stream" and "\r" in output.text:\n output.text = CR_PAT.sub("", output.text)\n\n cell.outputs = new_outputs\n return cell, resources\n | .venv\Lib\site-packages\nbconvert\preprocessors\coalescestreams.py | coalescestreams.py | Python | 1,385 | 0.95 | 0.222222 | 0.083333 | node-utils | 945 | 2025-03-03T21:50:29.441320 | BSD-3-Clause | false | fe1384109dabc3f37367b04690947021 |
"""Module containing a preprocessor that converts outputs in the notebook from\none format to another.\n\nConverts all of the outputs in a notebook from one format to another.\n"""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import Unicode\n\nfrom .base import Preprocessor\n\n\nclass ConvertFiguresPreprocessor(Preprocessor):\n """\n Converts all of the outputs in a notebook from one format to another.\n """\n\n from_format = Unicode(help="Format the converter accepts").tag(config=True)\n to_format = Unicode(help="Format the converter writes").tag(config=True)\n\n def __init__(self, **kw):\n """\n Public constructor\n """\n super().__init__(**kw)\n\n def convert_figure(self, data_format, data):\n """Convert the figure."""\n raise NotImplementedError()\n\n def preprocess_cell(self, cell, resources, cell_index):\n """\n Apply a transformation on each cell,\n\n See base.py\n """\n\n # Loop through all of the datatypes of the outputs in the cell.\n for output in cell.get("outputs", []):\n if (\n output.output_type in {"execute_result", "display_data"}\n and self.from_format in output.data\n and self.to_format not in output.data\n ):\n output.data[self.to_format] = self.convert_figure(\n self.from_format, output.data[self.from_format]\n )\n\n return cell, resources\n | .venv\Lib\site-packages\nbconvert\preprocessors\convertfigures.py | convertfigures.py | Python | 1,539 | 0.95 | 0.12 | 0.078947 | react-lib | 321 | 2024-05-31T22:17:14.198676 | BSD-3-Clause | false | 2b5106a1dd72d343499ff781812b3d95 |
"""Module that pre-processes the notebook for export to HTML."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport hashlib\nimport os\n\nfrom jupyterlab_pygments import JupyterStyle # type:ignore[import-untyped]\nfrom pygments.style import Style\nfrom traitlets import Type, Unicode, Union\n\nfrom .base import Preprocessor\n\ntry:\n from notebook import DEFAULT_STATIC_FILES_PATH # type:ignore[import-not-found]\nexcept ImportError:\n DEFAULT_STATIC_FILES_PATH = None\n\n\nclass CSSHTMLHeaderPreprocessor(Preprocessor):\n """\n Preprocessor used to pre-process notebook for HTML output. Adds IPython notebook\n front-end CSS and Pygments CSS to HTML output.\n """\n\n highlight_class = Unicode(".highlight", help="CSS highlight class identifier").tag(config=True)\n\n style = Union(\n [Unicode("default"), Type(klass=Style)],\n help="Name of the pygments style to use",\n default_value=JupyterStyle,\n ).tag(config=True)\n\n def __init__(self, *pargs, **kwargs):\n """Initialize the preprocessor."""\n Preprocessor.__init__(self, *pargs, **kwargs)\n self._default_css_hash = None\n\n def preprocess(self, nb, resources):\n """Fetch and add CSS to the resource dictionary\n\n Fetch CSS from IPython and Pygments to add at the beginning\n of the html files. Add this css in resources in the\n "inlining.css" key\n\n Parameters\n ----------\n nb : NotebookNode\n Notebook being converted\n resources : dictionary\n Additional resources used in the conversion process. Allows\n preprocessors to pass variables into the Jinja engine.\n """\n resources["inlining"] = {}\n resources["inlining"]["css"] = self._generate_header(resources)\n return nb, resources\n\n def _generate_header(self, resources):\n """\n Fills self.header with lines of CSS extracted from IPython\n and Pygments.\n """\n from pygments.formatters import HtmlFormatter\n\n header = []\n\n formatter = HtmlFormatter(style=self.style)\n pygments_css = formatter.get_style_defs(self.highlight_class)\n header.append(pygments_css)\n\n # Load the user's custom CSS and IPython's default custom CSS. If they\n # differ, assume the user has made modifications to his/her custom CSS\n # and that we should inline it in the nbconvert output.\n config_dir = resources["config_dir"]\n custom_css_filename = os.path.join(config_dir, "custom", "custom.css")\n if os.path.isfile(custom_css_filename):\n if DEFAULT_STATIC_FILES_PATH and self._default_css_hash is None:\n self._default_css_hash = self._hash(\n os.path.join(DEFAULT_STATIC_FILES_PATH, "custom", "custom.css")\n )\n if self._hash(custom_css_filename) != self._default_css_hash:\n with open(custom_css_filename, encoding="utf-8") as f:\n header.append(f.read())\n return header\n\n def _hash(self, filename):\n """Compute the hash of a file."""\n md5 = hashlib.md5() # noqa: S324\n with open(filename, "rb") as f:\n md5.update(f.read())\n return md5.digest()\n | .venv\Lib\site-packages\nbconvert\preprocessors\csshtmlheader.py | csshtmlheader.py | Python | 3,307 | 0.95 | 0.130435 | 0.067568 | node-utils | 82 | 2025-05-18T12:27:55.841543 | Apache-2.0 | false | 03f8555fb4308588726bfe0d5b5da2af |
# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Module containing a preprocessor that executes the code cells\nand updates outputs"""\n\nfrom __future__ import annotations\n\nimport typing as t\n\nfrom jupyter_client.manager import KernelManager\nfrom nbclient.client import NotebookClient\nfrom nbclient.client import execute as _execute\n\n# Backwards compatibility for imported name\nfrom nbclient.exceptions import CellExecutionError # noqa: F401\nfrom nbformat import NotebookNode\n\nfrom .base import Preprocessor\n\n\ndef executenb(*args, **kwargs):\n """DEPRECATED."""\n from warnings import warn\n\n warn(\n "The 'nbconvert.preprocessors.execute.executenb' function was moved to nbclient.execute. "\n "We recommend importing that library directly.",\n FutureWarning,\n stacklevel=2,\n )\n return _execute(*args, **kwargs)\n\n\n# We inherit from both classes to allow for traitlets to resolve as they did pre-6.0.\n# This unfortunately makes for some ugliness around initialization as NotebookClient\n# assumes it's a constructed class with a nb object that we have to hack around.\nclass ExecutePreprocessor(Preprocessor, NotebookClient):\n """\n Executes all the cells in a notebook\n """\n\n def __init__(self, **kw):\n """Initialize the preprocessor."""\n nb = kw.get("nb")\n if nb is None:\n nb = NotebookNode()\n Preprocessor.__init__(self, nb=nb, **kw)\n NotebookClient.__init__(self, nb, **kw)\n\n def _check_assign_resources(self, resources):\n if resources or not hasattr(self, "resources"):\n self.resources = resources\n\n def preprocess(\n self, nb: NotebookNode, resources: t.Any = None, km: KernelManager | None = None\n ) -> tuple[NotebookNode, dict[str, t.Any]]:\n """\n Preprocess notebook executing each code cell.\n\n The input argument *nb* is modified in-place.\n\n Note that this function recalls NotebookClient.__init__, which may look wrong.\n However since the preprocess call acts line an init on execution state it's expected.\n Therefore, we need to capture it here again to properly reset because traitlet\n assignments are not passed. There is a risk if traitlets apply any side effects for\n dual init.\n The risk should be manageable, and this approach minimizes side-effects relative\n to other alternatives.\n\n One alternative but rejected implementation would be to copy the client's init internals\n which has already gotten out of sync with nbclient 0.5 release before nbconvert 6.0 released.\n\n Parameters\n ----------\n nb : NotebookNode\n Notebook being executed.\n resources : dictionary (optional)\n Additional resources used in the conversion process. For example,\n passing ``{'metadata': {'path': run_path}}`` sets the\n execution path to ``run_path``.\n km: KernelManager (optional)\n Optional kernel manager. If none is provided, a kernel manager will\n be created.\n\n Returns\n -------\n nb : NotebookNode\n The executed notebook.\n resources : dictionary\n Additional resources used in the conversion process.\n """\n NotebookClient.__init__(self, nb, km)\n self.reset_execution_trackers()\n self._check_assign_resources(resources)\n\n with self.setup_kernel():\n assert self.kc\n info_msg = self.wait_for_reply(self.kc.kernel_info())\n assert info_msg\n self.nb.metadata["language_info"] = info_msg["content"]["language_info"]\n for index, cell in enumerate(self.nb.cells):\n self.preprocess_cell(cell, resources, index)\n self.set_widgets_metadata()\n\n return self.nb, self.resources\n\n def preprocess_cell(self, cell, resources, index):\n """\n Override if you want to apply some preprocessing to each cell.\n Must return modified cell and resource dictionary.\n\n Parameters\n ----------\n cell : NotebookNode cell\n Notebook cell being processed\n resources : dictionary\n Additional resources used in the conversion process. Allows\n preprocessors to pass variables into the Jinja engine.\n index : int\n Index of the cell being processed\n """\n self._check_assign_resources(resources)\n cell = self.execute_cell(cell, index, store_history=True)\n return cell, self.resources\n | .venv\Lib\site-packages\nbconvert\preprocessors\execute.py | execute.py | Python | 4,604 | 0.95 | 0.144 | 0.058824 | python-kit | 287 | 2024-12-29T02:33:40.940850 | MIT | false | 9ff1dda1fce954f18a13269a57b72d20 |
"""\nModule that extracts attachments from notebooks into their own files\n"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport os\nfrom base64 import b64decode\n\nfrom traitlets import Bool, Unicode\n\nfrom .base import Preprocessor\n\n\nclass ExtractAttachmentsPreprocessor(Preprocessor):\n """\n Extracts attachments from all (markdown and raw) cells in a notebook.\n The extracted attachments are stored in a directory ('attachments' by default).\n https://nbformat.readthedocs.io/en/latest/format_description.html#cell-attachments\n """\n\n attachments_directory_template = Unicode(\n "{notebook_name}_attachments",\n help="Directory to place attachments if use_separate_dir is True",\n ).tag(config=True)\n\n use_separate_dir = Bool(\n False,\n help="Whether to use output_files_dir (which ExtractOutput also uses) or "\n "create a separate directory for attachments",\n ).tag(config=True)\n\n def __init__(self, **kw):\n """\n Public constructor\n """\n super().__init__(**kw)\n # directory path,\n self.path_name = "" # will be set in self.preprocess, needs resources\n # Where extracted attachments are stored in resources\n self.resources_item_key = (\n "attachments" # Here as a default, in case someone doesn't want to call preprocess\n )\n\n # Add condition and configurability here\n def preprocess(self, nb, resources):\n """\n Determine some settings and apply preprocessor to notebook\n """\n if self.use_separate_dir:\n self.path_name = self.attachments_directory_template.format(\n notebook_name=resources["unique_key"]\n )\n # Initialize resources for attachments\n resources["attachment_files_dir"] = self.path_name\n resources["attachments"] = {}\n self.resources_item_key = "attachments"\n else:\n # Use same resources as ExtractOutput\n self.path_name = resources["output_files_dir"]\n self.resources_item_key = "outputs"\n\n # Make sure key exists\n if not isinstance(resources[self.resources_item_key], dict):\n resources[self.resources_item_key] = {}\n\n nb, resources = super().preprocess(nb, resources)\n return nb, resources\n\n def preprocess_cell(self, cell, resources, index):\n """\n Extract attachments to individual files and\n change references to them.\n E.g.\n ''\n becomes\n ''\n Assumes self.path_name and self.resources_item_key is set properly (usually in preprocess).\n """\n if "attachments" in cell:\n for fname in cell.attachments:\n self.log.debug("Encountered attachment %s", fname)\n\n # Add file for writer\n\n # Right now I don't know of a situation where there would be multiple\n # mime types under same filename, and I can't index into it without the mimetype.\n # So I only read the first one.\n for mimetype in cell.attachments[fname]:\n # convert to bytes and decode\n data = cell.attachments[fname][mimetype].encode("utf-8")\n decoded = b64decode(data)\n break\n\n # FilesWriter wants path to be in attachment filename here\n new_filename = os.path.join(self.path_name, fname)\n resources[self.resources_item_key][new_filename] = decoded\n\n # Edit the reference to the attachment\n\n # os.path.join on windows uses "\\" separator,\n # but files like markdown still want "/"\n if os.path.sep != "/":\n new_filename = new_filename.replace(os.path.sep, "/")\n cell.source = cell.source.replace("attachment:" + fname, new_filename)\n\n return cell, resources\n | .venv\Lib\site-packages\nbconvert\preprocessors\extractattachments.py | extractattachments.py | Python | 4,080 | 0.95 | 0.12963 | 0.191011 | vue-tools | 822 | 2023-09-18T12:09:06.686636 | MIT | false | 78ce50bef22ba5701c0990bd3b4889d2 |
"""A preprocessor that extracts all of the outputs from the\nnotebook file. The extracted outputs are returned in the 'resources' dictionary.\n"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport json\nimport os\nimport sys\nfrom binascii import a2b_base64\nfrom mimetypes import guess_extension\nfrom textwrap import dedent\n\nfrom traitlets import Set, Unicode\n\nfrom .base import Preprocessor\n\n\ndef guess_extension_without_jpe(mimetype):\n """\n This function fixes a problem with '.jpe' extensions\n of jpeg images which are then not recognised by latex.\n For any other case, the function works in the same way\n as mimetypes.guess_extension\n """\n ext = guess_extension(mimetype)\n if ext == ".jpe":\n ext = ".jpeg"\n return ext\n\n\ndef platform_utf_8_encode(data):\n """Encode data based on platform."""\n if isinstance(data, str):\n if sys.platform == "win32":\n data = data.replace("\n", "\r\n")\n data = data.encode("utf-8")\n return data\n\n\nclass ExtractOutputPreprocessor(Preprocessor):\n """\n Extracts all of the outputs from the notebook file. The extracted\n outputs are returned in the 'resources' dictionary.\n """\n\n output_filename_template = Unicode("{unique_key}_{cell_index}_{index}{extension}").tag(\n config=True\n )\n\n extract_output_types = Set({"image/png", "image/jpeg", "image/svg+xml", "application/pdf"}).tag(\n config=True\n )\n\n def preprocess_cell(self, cell, resources, cell_index):\n """\n Apply a transformation on each cell,\n\n Parameters\n ----------\n cell : NotebookNode cell\n Notebook cell being processed\n resources : dictionary\n Additional resources used in the conversion process. Allows\n preprocessors to pass variables into the Jinja engine.\n cell_index : int\n Index of the cell being processed (see base.py)\n """\n\n # Get the unique key from the resource dict if it exists. If it does not\n # exist, use 'output' as the default. Also, get files directory if it\n # has been specified\n unique_key = resources.get("unique_key", "output")\n output_files_dir = resources.get("output_files_dir", None)\n\n # Make sure outputs key exists\n if not isinstance(resources["outputs"], dict):\n resources["outputs"] = {}\n\n # Loop through all of the outputs in the cell\n for index, out in enumerate(cell.get("outputs", [])):\n if out.output_type not in {"display_data", "execute_result"}:\n continue\n if "text/html" in out.data:\n out["data"]["text/html"] = dedent(out["data"]["text/html"])\n # Get the output in data formats that the template needs extracted\n for mime_type in self.extract_output_types:\n if mime_type in out.data:\n data = out.data[mime_type]\n\n # Binary files are base64-encoded, SVG is already XML\n if mime_type in {"image/png", "image/jpeg", "application/pdf"}:\n # data is b64-encoded as text (str, unicode),\n # we want the original bytes\n data = a2b_base64(data)\n elif mime_type == "application/json" or not isinstance(data, str):\n # Data is either JSON-like and was parsed into a Python\n # object according to the spec, or data is for sure\n # JSON. In the latter case we want to go extra sure that\n # we enclose a scalar string value into extra quotes by\n # serializing it properly.\n if isinstance(data, bytes):\n # We need to guess the encoding in this\n # instance. Some modules that return raw data like\n # svg can leave the data in byte form instead of str\n data = data.decode("utf-8")\n data = platform_utf_8_encode(json.dumps(data))\n else:\n # All other text_type data will fall into this path\n data = platform_utf_8_encode(data)\n\n ext = guess_extension_without_jpe(mime_type)\n if ext is None:\n ext = "." + mime_type.rsplit("/")[-1]\n if out.metadata.get("filename", ""):\n filename = out.metadata["filename"]\n if not filename.endswith(ext):\n filename += ext\n else:\n filename = self.output_filename_template.format(\n unique_key=unique_key, cell_index=cell_index, index=index, extension=ext\n )\n\n # On the cell, make the figure available via\n # cell.outputs[i].metadata.filenames['mime/type']\n # where\n # cell.outputs[i].data['mime/type'] contains the data\n if output_files_dir is not None:\n filename = os.path.join(output_files_dir, filename)\n out.metadata.setdefault("filenames", {})\n out.metadata["filenames"][mime_type] = filename\n\n if filename in resources["outputs"]:\n msg = (\n "Your outputs have filename metadata associated "\n "with them. Nbconvert saves these outputs to "\n "external files using this filename metadata. "\n "Filenames need to be unique across the notebook, "\n f"or images will be overwritten. The filename {filename} is "\n "associated with more than one output. The second "\n "output associated with this filename is in cell "\n f"{cell_index}."\n )\n raise ValueError(msg)\n # In the resources, make the figure available via\n # resources['outputs']['filename'] = data\n resources["outputs"][filename] = data\n\n return cell, resources\n | .venv\Lib\site-packages\nbconvert\preprocessors\extractoutput.py | extractoutput.py | Python | 6,445 | 0.95 | 0.166667 | 0.203125 | node-utils | 82 | 2024-03-08T12:44:21.216042 | GPL-3.0 | false | b85a50e12ee89cba3dcea8041d1b3bd3 |
"""This preprocessor detect cells using a different language through\nmagic extensions such as `%%R` or `%%octave`. Cell's metadata is marked\nso that the appropriate highlighter can be used in the `highlight`\nfilter.\n"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport re\n\nfrom traitlets import Dict\n\nfrom .base import Preprocessor\n\n\nclass HighlightMagicsPreprocessor(Preprocessor):\n """\n Detects and tags code cells that use a different languages than Python.\n """\n\n # list of magic language extensions and their associated pygment lexers\n default_languages = Dict(\n {\n "%%R": "r",\n "%%bash": "bash",\n "%%cython": "cython",\n "%%javascript": "javascript",\n "%%julia": "julia",\n "%%latex": "latex",\n "%%octave": "octave",\n "%%perl": "perl",\n "%%ruby": "ruby",\n "%%sh": "sh",\n "%%sql": "sql",\n }\n )\n\n # user defined language extensions\n languages = Dict(\n help=(\n "Syntax highlighting for magic's extension languages. "\n "Each item associates a language magic extension such as %%R, "\n "with a pygments lexer such as r."\n )\n ).tag(config=True)\n\n def __init__(self, config=None, **kw):\n """Public constructor"""\n\n super().__init__(config=config, **kw)\n\n # Update the default languages dict with the user configured ones\n self.default_languages.update(self.languages)\n\n # build a regular expression to catch language extensions and choose\n # an adequate pygments lexer\n any_language = "|".join(self.default_languages.keys())\n self.re_magic_language = re.compile(rf"^\s*({any_language})\s+")\n\n def which_magic_language(self, source):\n """\n When a cell uses another language through a magic extension,\n the other language is returned.\n If no language magic is detected, this function returns None.\n\n Parameters\n ----------\n source: str\n Source code of the cell to highlight\n """\n\n m = self.re_magic_language.match(source)\n\n if m:\n # By construction of the re, the matched language must be in the\n # languages dictionary\n return self.default_languages[m.group(1)]\n return None\n\n def preprocess_cell(self, cell, resources, cell_index):\n """\n Tags cells using a magic extension language\n\n Parameters\n ----------\n cell : NotebookNode cell\n Notebook cell being processed\n resources : dictionary\n Additional resources used in the conversion process. Allows\n preprocessors to pass variables into the Jinja engine.\n cell_index : int\n Index of the cell being processed (see base.py)\n """\n\n # Only tag code cells\n if cell.cell_type == "code":\n magic_language = self.which_magic_language(cell.source)\n if magic_language:\n cell["metadata"]["magics_language"] = magic_language\n return cell, resources\n | .venv\Lib\site-packages\nbconvert\preprocessors\highlightmagics.py | highlightmagics.py | Python | 3,197 | 0.95 | 0.09901 | 0.121951 | react-lib | 7 | 2025-04-01T15:29:00.470114 | MIT | false | 9192335846486d31e84570613ee3e3ca |
"""Module that allows latex output notebooks to be conditioned before\nthey are converted.\n"""\n# -----------------------------------------------------------------------------\n# Copyright (c) 2013, the IPython Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# -----------------------------------------------------------------------------\n\n# -----------------------------------------------------------------------------\n# Imports\n# -----------------------------------------------------------------------------\n\nfrom traitlets import List, Unicode\n\nfrom .base import Preprocessor\n\n# -----------------------------------------------------------------------------\n# Classes\n# -----------------------------------------------------------------------------\n\n\nclass LatexPreprocessor(Preprocessor):\n """Preprocessor for latex destined documents.\n\n Populates the ``latex`` key in the resources dict,\n adding definitions for pygments highlight styles.\n\n Sets the authors, date and title of the latex document,\n overriding the values given in the metadata.\n """\n\n date = Unicode(\n None,\n help=("Date of the LaTeX document"),\n allow_none=True,\n ).tag(config=True)\n\n title = Unicode(None, help=("Title of the LaTeX document"), allow_none=True).tag(config=True)\n\n author_names = List(\n Unicode(),\n default_value=None,\n help=("Author names to list in the LaTeX document"),\n allow_none=True,\n ).tag(config=True)\n\n style = Unicode("default", help="Name of the pygments style to use").tag(config=True)\n\n def preprocess(self, nb, resources):\n """Preprocessing to apply on each notebook.\n\n Parameters\n ----------\n nb : NotebookNode\n Notebook being converted\n resources : dictionary\n Additional resources used in the conversion process. Allows\n preprocessors to pass variables into the Jinja engine.\n """\n # Generate Pygments definitions for Latex\n from pygments.formatters import LatexFormatter\n\n resources.setdefault("latex", {})\n resources["latex"].setdefault(\n "pygments_definitions", LatexFormatter(style=self.style).get_style_defs()\n )\n resources["latex"].setdefault("pygments_style_name", self.style)\n\n if self.author_names is not None:\n nb.metadata["authors"] = [{"name": author} for author in self.author_names]\n\n if self.date is not None:\n nb.metadata["date"] = self.date\n\n if self.title is not None:\n nb.metadata["title"] = self.title\n\n return nb, resources\n | .venv\Lib\site-packages\nbconvert\preprocessors\latex.py | latex.py | Python | 2,735 | 0.95 | 0.111111 | 0.225806 | vue-tools | 198 | 2025-05-19T10:50:38.369521 | Apache-2.0 | false | 46981a076a7da6a29aa6c77b640ba452 |
"""\nModule containing a preprocessor that removes cells if they match\none or more regular expression.\n"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport re\n\nfrom traitlets import List, Unicode\n\nfrom .base import Preprocessor\n\n\nclass RegexRemovePreprocessor(Preprocessor):\n """\n Removes cells from a notebook that match one or more regular expression.\n\n For each cell, the preprocessor checks whether its contents match\n the regular expressions in the ``patterns`` traitlet which is a list\n of unicode strings. If the contents match any of the patterns, the cell\n is removed from the notebook.\n\n To modify the list of matched patterns,\n modify the patterns traitlet. For example, execute the following command\n to convert a notebook to html and remove cells containing only whitespace::\n\n jupyter nbconvert --RegexRemovePreprocessor.patterns="['\\s*\\Z']" mynotebook.ipynb\n\n The command line argument\n sets the list of patterns to ``'\\s*\\Z'`` which matches an arbitrary number\n of whitespace characters followed by the end of the string.\n\n See https://regex101.com/ for an interactive guide to regular expressions\n (make sure to select the python flavor). See\n https://docs.python.org/library/re.html for the official regular expression\n documentation in python.\n """\n\n patterns = List(Unicode()).tag(config=True)\n\n def check_conditions(self, cell):\n """\n Checks that a cell matches the pattern.\n\n Returns: Boolean.\n True means cell should *not* be removed.\n """\n\n # Compile all the patterns into one: each pattern is first wrapped\n # by a non-capturing group to ensure the correct order of precedence\n # and the patterns are joined with a logical or\n pattern = re.compile("|".join("(?:%s)" % pattern for pattern in self.patterns))\n\n # Filter out cells that meet the pattern and have no outputs\n return not pattern.match(cell.source)\n\n def preprocess(self, nb, resources):\n """\n Preprocessing to apply to each notebook. See base.py for details.\n """\n # Skip preprocessing if the list of patterns is empty\n if not self.patterns:\n return nb, resources\n\n # Filter out cells that meet the conditions\n nb.cells = [cell for cell in nb.cells if self.check_conditions(cell)]\n\n return nb, resources\n | .venv\Lib\site-packages\nbconvert\preprocessors\regexremove.py | regexremove.py | Python | 2,498 | 0.95 | 0.169014 | 0.153846 | python-kit | 591 | 2024-05-26T08:10:24.921356 | Apache-2.0 | false | c2b5cf8f143c0b36de6c303da3bbf97c |
"""\nNBConvert Preprocessor for sanitizing HTML rendering of notebooks.\n"""\n\nimport warnings\n\nfrom bleach import ALLOWED_ATTRIBUTES, ALLOWED_TAGS, clean\nfrom traitlets import Any, Bool, List, Set, Unicode\n\nfrom .base import Preprocessor\n\n_USE_BLEACH_CSS_SANITIZER = False\n_USE_BLEACH_STYLES = False\n\n\ntry:\n # bleach[css] >=5.0\n from bleach.css_sanitizer import ALLOWED_CSS_PROPERTIES as ALLOWED_STYLES\n from bleach.css_sanitizer import CSSSanitizer\n\n _USE_BLEACH_CSS_SANITIZER = True\n _USE_BLEACH_STYLES = False\nexcept ImportError:\n try:\n # bleach <5\n from bleach import ALLOWED_STYLES # type:ignore[attr-defined, no-redef]\n\n _USE_BLEACH_CSS_SANITIZER = False\n _USE_BLEACH_STYLES = True\n warnings.warn(\n "Support for bleach <5 will be removed in a future version of nbconvert",\n DeprecationWarning,\n stacklevel=2,\n )\n\n except ImportError:\n warnings.warn(\n "The installed bleach/tinycss2 do not provide CSS sanitization, "\n "please upgrade to bleach >=5",\n UserWarning,\n stacklevel=2,\n )\n\n\n__all__ = ["SanitizeHTML"]\n\n\nclass SanitizeHTML(Preprocessor):\n """A preprocessor to sanitize html."""\n\n # Bleach config.\n attributes = Any(\n config=True,\n default_value=ALLOWED_ATTRIBUTES,\n help="Allowed HTML tag attributes",\n )\n tags = List(\n Unicode(),\n config=True,\n default_value=ALLOWED_TAGS, # type:ignore[arg-type]\n help="List of HTML tags to allow",\n )\n styles = List(\n Unicode(),\n config=True,\n default_value=ALLOWED_STYLES, # type:ignore[arg-type]\n help="Allowed CSS styles if <style> tag is allowed",\n )\n strip = Bool(\n config=True,\n default_value=False,\n help="If True, remove unsafe markup entirely instead of escaping",\n )\n strip_comments = Bool(\n config=True,\n default_value=True,\n help="If True, strip comments from escaped HTML",\n )\n\n # Display data config.\n safe_output_keys = Set(\n config=True,\n default_value={\n "metadata", # Not a mimetype per-se, but expected and safe.\n "text/plain",\n "text/latex",\n "application/json",\n "image/png",\n "image/jpeg",\n },\n help="Cell output mimetypes to render without modification",\n )\n sanitized_output_types = Set(\n config=True,\n default_value={\n "text/html",\n "text/markdown",\n },\n help="Cell output types to display after escaping with Bleach.",\n )\n\n def preprocess_cell(self, cell, resources, cell_index):\n """\n Sanitize potentially-dangerous contents of the cell.\n\n Cell Types:\n raw:\n Sanitize literal HTML\n markdown:\n Sanitize literal HTML\n code:\n Sanitize outputs that could result in code execution\n """\n if cell.cell_type == "raw":\n # Sanitize all raw cells anyway.\n # Only ones with the text/html mimetype should be emitted\n # but erring on the side of safety maybe.\n cell.source = self.sanitize_html_tags(cell.source)\n return cell, resources\n if cell.cell_type == "markdown":\n cell.source = self.sanitize_html_tags(cell.source)\n return cell, resources\n if cell.cell_type == "code":\n cell.outputs = self.sanitize_code_outputs(cell.outputs)\n return cell, resources\n return None\n\n def sanitize_code_outputs(self, outputs):\n """\n Sanitize code cell outputs.\n\n Removes 'text/javascript' fields from display_data outputs, and\n runs `sanitize_html_tags` over 'text/html'.\n """\n for output in outputs:\n # These are always ascii, so nothing to escape.\n if output["output_type"] in ("stream", "error"):\n continue\n data = output.data\n to_remove = []\n for key in data:\n if key in self.safe_output_keys:\n continue\n if key in self.sanitized_output_types:\n self.log.info("Sanitizing %s", key)\n data[key] = self.sanitize_html_tags(data[key])\n else:\n # Mark key for removal. (Python doesn't allow deletion of\n # keys from a dict during iteration)\n to_remove.append(key)\n for key in to_remove:\n self.log.info("Removing %s", key)\n del data[key]\n return outputs\n\n def sanitize_html_tags(self, html_str):\n """\n Sanitize a string containing raw HTML tags.\n """\n kwargs = {\n "tags": self.tags,\n "attributes": self.attributes,\n "strip": self.strip,\n "strip_comments": self.strip_comments,\n }\n\n if _USE_BLEACH_CSS_SANITIZER:\n css_sanitizer = CSSSanitizer(allowed_css_properties=self.styles)\n kwargs.update(css_sanitizer=css_sanitizer)\n elif _USE_BLEACH_STYLES:\n kwargs.update(styles=self.styles)\n\n return clean(html_str, **kwargs)\n\n\ndef _get_default_css_sanitizer():\n if _USE_BLEACH_CSS_SANITIZER:\n return CSSSanitizer(allowed_css_properties=ALLOWED_STYLES)\n return None\n | .venv\Lib\site-packages\nbconvert\preprocessors\sanitize.py | sanitize.py | Python | 5,463 | 0.95 | 0.122905 | 0.064516 | node-utils | 593 | 2024-04-07T03:39:46.421079 | Apache-2.0 | false | 5e40265e58eac052bff3878c49b67662 |
"""Module containing a preprocessor that converts outputs in the notebook from\none format to another.\n"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport base64\nimport os\nimport subprocess\nimport sys\nfrom shutil import which\nfrom tempfile import TemporaryDirectory\n\nfrom traitlets import List, Unicode, Union, default\n\nfrom nbconvert.utils.io import FormatSafeDict\n\nfrom .convertfigures import ConvertFiguresPreprocessor\n\n# inkscape path for darwin (macOS)\nINKSCAPE_APP = "/Applications/Inkscape.app/Contents/Resources/bin/inkscape"\n# Recent versions of Inkscape (v1.0) moved the executable from\n# Resources/bin/inkscape to MacOS/inkscape\nINKSCAPE_APP_v1 = "/Applications/Inkscape.app/Contents/MacOS/inkscape"\n\nif sys.platform == "win32":\n try:\n import winreg\n except ImportError:\n import _winreg as winreg\n\n\nclass SVG2PDFPreprocessor(ConvertFiguresPreprocessor):\n """\n Converts all of the outputs in a notebook from SVG to PDF.\n """\n\n @default("from_format")\n def _from_format_default(self):\n return "image/svg+xml"\n\n @default("to_format")\n def _to_format_default(self):\n return "application/pdf"\n\n inkscape_version = Unicode(\n help="""The version of inkscape being used.\n\n This affects how the conversion command is run.\n """\n ).tag(config=True)\n\n @default("inkscape_version")\n def _inkscape_version_default(self):\n p = subprocess.Popen(\n [self.inkscape, "--version"], # noqa:S603\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n output, _ = p.communicate()\n if p.returncode != 0:\n msg = "Unable to find inkscape executable --version"\n raise RuntimeError(msg)\n return output.decode("utf-8").split(" ")[1]\n\n # FIXME: Deprecate passing a string here\n command = Union(\n [Unicode(), List()],\n help="""\n The command to use for converting SVG to PDF\n\n This traitlet is a template, which will be formatted with the keys\n to_filename and from_filename.\n\n The conversion call must read the SVG from {from_filename},\n and write a PDF to {to_filename}.\n\n It could be a List (recommended) or a String. If string, it will\n be passed to a shell for execution.\n """,\n ).tag(config=True)\n\n @default("command")\n def _command_default(self):\n major_version = self.inkscape_version.split(".")[0]\n command = [self.inkscape]\n\n if int(major_version) < 1:\n # --without-gui is only needed for inkscape 0.x\n command.append("--without-gui")\n # --export-pdf is old name for --export-filename\n command.append("--export-pdf={to_filename}")\n else:\n command.append("--export-filename={to_filename}")\n\n command.append("{from_filename}")\n return command\n\n inkscape = Unicode(help="The path to Inkscape, if necessary").tag(config=True)\n\n @default("inkscape")\n def _inkscape_default(self):\n inkscape_path = which("inkscape")\n if inkscape_path is not None:\n return inkscape_path\n if sys.platform == "darwin":\n if os.path.isfile(INKSCAPE_APP_v1):\n return INKSCAPE_APP_v1\n # Order is important. If INKSCAPE_APP exists, prefer it over\n # the executable in the MacOS directory.\n if os.path.isfile(INKSCAPE_APP):\n return INKSCAPE_APP\n if sys.platform == "win32":\n wr_handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)\n try:\n rkey = winreg.OpenKey(wr_handle, "SOFTWARE\\Classes\\inkscape.svg\\DefaultIcon")\n inkscape = winreg.QueryValueEx(rkey, "")[0]\n except FileNotFoundError:\n msg = "Inkscape executable not found"\n raise FileNotFoundError(msg) from None\n return inkscape\n return "inkscape"\n\n def convert_figure(self, data_format, data):\n """\n Convert a single SVG figure to PDF. Returns converted data.\n """\n\n # Work in a temporary directory\n with TemporaryDirectory() as tmpdir:\n # Write fig to temp file\n input_filename = os.path.join(tmpdir, "figure.svg")\n # SVG data is unicode text\n with open(input_filename, "w", encoding="utf8") as f:\n f.write(data)\n\n # Call conversion application\n output_filename = os.path.join(tmpdir, "figure.pdf")\n\n template_vars = {"from_filename": input_filename, "to_filename": output_filename}\n if isinstance(self.command, list):\n full_cmd = [s.format_map(FormatSafeDict(**template_vars)) for s in self.command]\n else:\n # For backwards compatibility with specifying strings\n # Okay-ish, since the string is trusted\n full_cmd = self.command.format(*template_vars)\n subprocess.call(full_cmd, shell=isinstance(full_cmd, str)) # noqa: S603\n\n # Read output from drive\n # return value expects a filename\n if os.path.isfile(output_filename):\n with open(output_filename, "rb") as f:\n # PDF is a nb supported binary, data type, so base64 encode.\n return base64.encodebytes(f.read()).decode("utf-8")\n else:\n msg = "Inkscape svg to pdf conversion failed"\n raise TypeError(msg)\n | .venv\Lib\site-packages\nbconvert\preprocessors\svg2pdf.py | svg2pdf.py | Python | 5,589 | 0.95 | 0.164557 | 0.146154 | awesome-app | 153 | 2024-06-03T01:44:37.770185 | GPL-3.0 | false | c73829588b0ecfacf2c7b7107a3ad14c |
"""\nModule containing a preprocessor that removes cells if they match\none or more regular expression.\n"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nfrom traitlets import Set, Unicode\n\nfrom .base import Preprocessor\n\n\nclass TagRemovePreprocessor(Preprocessor):\n """\n Removes inputs, outputs, or cells from a notebook that\n have tags that designate they are to be removed prior to exporting\n the notebook.\n\n remove_cell_tags\n removes cells tagged with these values\n\n remove_all_outputs_tags\n removes entire output areas on cells\n tagged with these values\n\n remove_single_output_tags\n removes individual output objects on\n outputs tagged with these values\n\n remove_input_tags\n removes inputs tagged with these values\n """\n\n remove_cell_tags: set[str] = Set( # type:ignore[assignment]\n Unicode(),\n default_value=[],\n help=(\n "Tags indicating which cells are to be removed,"\n "matches tags in ``cell.metadata.tags``."\n ),\n ).tag(config=True)\n remove_all_outputs_tags: set[str] = Set( # type:ignore[assignment]\n Unicode(),\n default_value=[],\n help=(\n "Tags indicating cells for which the outputs are to be removed,"\n "matches tags in ``cell.metadata.tags``."\n ),\n ).tag(config=True)\n remove_single_output_tags: set[str] = Set( # type:ignore[assignment]\n Unicode(),\n default_value=[],\n help=(\n "Tags indicating which individual outputs are to be removed,"\n "matches output *i* tags in ``cell.outputs[i].metadata.tags``."\n ),\n ).tag(config=True)\n remove_input_tags: set[str] = Set( # type:ignore[assignment]\n Unicode(),\n default_value=[],\n help=(\n "Tags indicating cells for which input is to be removed,"\n "matches tags in ``cell.metadata.tags``."\n ),\n ).tag(config=True)\n remove_metadata_fields: set[str] = Set({"collapsed", "scrolled"}).tag(config=True) # type:ignore[assignment]\n\n def check_cell_conditions(self, cell, resources, index):\n """\n Checks that a cell has a tag that is to be removed\n\n Returns: Boolean.\n True means cell should *not* be removed.\n """\n\n # Return true if any of the tags in the cell are removable.\n return not self.remove_cell_tags.intersection(cell.get("metadata", {}).get("tags", []))\n\n def preprocess(self, nb, resources):\n """\n Preprocessing to apply to each notebook. See base.py for details.\n """\n # Skip preprocessing if the list of patterns is empty\n if not any(\n [\n self.remove_cell_tags,\n self.remove_all_outputs_tags,\n self.remove_single_output_tags,\n self.remove_input_tags,\n ]\n ):\n return nb, resources\n\n # Filter out cells that meet the conditions\n nb.cells = [\n self.preprocess_cell(cell, resources, index)[0]\n for index, cell in enumerate(nb.cells)\n if self.check_cell_conditions(cell, resources, index)\n ]\n\n return nb, resources\n\n def preprocess_cell(self, cell, resources, cell_index):\n """\n Apply a transformation on each cell. See base.py for details.\n """\n\n if (\n self.remove_all_outputs_tags.intersection(cell.get("metadata", {}).get("tags", []))\n and cell.cell_type == "code"\n ):\n cell.outputs = []\n cell.execution_count = None\n # Remove metadata associated with output\n if "metadata" in cell:\n for field in self.remove_metadata_fields:\n cell.metadata.pop(field, None)\n\n if self.remove_input_tags.intersection(cell.get("metadata", {}).get("tags", [])):\n cell.metadata["transient"] = {"remove_source": True}\n\n if cell.get("outputs", []):\n cell.outputs = [\n output\n for output_index, output in enumerate(cell.outputs)\n if self.check_output_conditions(output, resources, cell_index, output_index)\n ]\n return cell, resources\n\n def check_output_conditions(self, output, resources, cell_index, output_index):\n """\n Checks that an output has a tag that indicates removal.\n\n Returns: Boolean.\n True means output should *not* be removed.\n """\n return not self.remove_single_output_tags.intersection(\n output.get("metadata", {}).get("tags", [])\n )\n | .venv\Lib\site-packages\nbconvert\preprocessors\tagremove.py | tagremove.py | Python | 4,731 | 0.95 | 0.156028 | 0.05042 | vue-tools | 984 | 2025-03-16T16:02:59.575380 | BSD-3-Clause | false | aff8c9adb85a6e3d00f8289ea9d246c4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.