| 1 |
"""Module for handling different functions to read "notebook-like" files.""" |
| 2 |
from typing import Any, Callable, Dict, Set |
| 3 |
|
| 4 |
import nbformat as nbf |
| 5 |
|
| 6 |
from .entry_points import ENTRY_POINT_GROUP_READER, get_entry_point, list_group_names |
| 7 |
|
| 8 |
DEFAULT_READ_DATA = (("name", "nbformat"), ("type", "plugin")) |
| 9 |
|
| 10 |
|
| 11 |
def nbf_reader(uri: str) -> nbf.NotebookNode: |
| 12 |
"""Standard notebook reader.""" |
| 13 |
return nbf.read(uri, nbf.NO_CONVERT) |
| 14 |
|
| 15 |
|
| 16 |
def jupytext_reader(uri: str) -> nbf.NotebookNode: |
| 17 |
"""Jupytext notebook reader.""" |
| 18 |
try: |
| 19 |
import jupytext |
| 20 |
except ImportError: |
| 21 |
raise ImportError("jupytext must be installed to use this reader") |
| 22 |
return jupytext.read(uri) |
| 23 |
|
| 24 |
|
| 25 |
def list_readers() -> Set[str]: |
| 26 |
"""List all available readers.""" |
| 27 |
return list_group_names(ENTRY_POINT_GROUP_READER) |
| 28 |
|
| 29 |
|
| 30 |
def get_reader(data: Dict[str, Any]) -> Callable[[str], nbf.NotebookNode]: |
| 31 |
"""Returns a function to read a file URI and return a notebook.""" |
| 32 |
if data.get("type") == "plugin": |
| 33 |
key = data.get("name", "") |
| 34 |
reader = get_entry_point(ENTRY_POINT_GROUP_READER, key) |
| 35 |
if reader is not None: |
| 36 |
return reader.load() |
| 37 |
raise ValueError(f"No reader found for: {data!r}") |
| 38 |
|
| 39 |
|
| 40 |
class NbReadError(IOError): |
| 41 |
"""Error raised when a notebook cannot be read.""" |