1 1
import logging
2

3 1
import traitlets as traits
4 1
from nbconvert.preprocessors import Preprocessor
5 1
from nbformat.notebooknode import NotebookNode
6

7 1
logger = logging.getLogger("captions")
8

9

10 1
class LatexCaptions(Preprocessor):
11
    """ a preprocessor to:
12

13
    1. find cells with a ipub.caption meta-tag,
14
       extract the caption and label to a dict and remove the cell
15
    2. find cells with the found labels and replace their captions
16

17
    """
18

19 1
    add_prefix = traits.Bool(
20
        False,
21
        help=("add float type/number prefix to caption " "(from caption_prefix tag)"),
22
    ).tag(config=True)
23

24 1
    def preprocess(self, nb, resources):
25

26 1
        logger.info("extracting caption cells")
27

28
        # extract captions
29 1
        final_cells = []
30 1
        captions = {}
31 1
        for cell in nb.cells:
32 1
            if hasattr(cell.metadata, "ipub"):
33

34 1
                if hasattr(cell.metadata.ipub.get("equation", False), "get"):
35 1
                    if hasattr(
36
                        cell.metadata.ipub.equation.get("environment", False),
37
                        "startswith",
38
                    ):
39 1
                        if cell.metadata.ipub.equation.environment.startswith(
40
                            "breqn"
41
                        ):  # noqa: E501
42 0
                            if "ipub" not in nb.metadata:
43 0
                                nb.metadata["ipub"] = NotebookNode(
44
                                    {"enable_breqn": True}
45
                                )
46
                            else:
47 0
                                nb.metadata.ipub["enable_breqn"] = True
48

49 1
                if hasattr(cell.metadata.ipub, "caption"):
50

51 1
                    if cell.cell_type == "markdown":
52 1
                        capt = cell.source.split(r"\n")[0]
53 1
                        captions[cell.metadata.ipub.caption] = capt
54 1
                        continue
55 0
                    elif cell.cell_type == "code":
56 0
                        if not cell.outputs:
57 0
                            pass
58 0
                        elif "text/latex" in cell.outputs[0].get("data", {}):
59 0
                            capt = cell.outputs[0].data["text/latex"].split(r"\n")[0]
60 0
                            captions[cell.metadata.ipub.caption] = capt
61 0
                            continue
62 0
                        elif "text/plain" in cell.outputs[0].get("data", {}):
63 0
                            capt = cell.outputs[0].data["text/plain"].split(r"\n")[0]
64 0
                            captions[cell.metadata.ipub.caption] = capt
65 0
                            continue
66

67 1
            final_cells.append(cell)
68 1
        nb.cells = final_cells
69

70
        # replace captions
71 1
        for cell in nb.cells:
72 1
            if hasattr(cell.metadata, "ipub"):
73 1
                for key in cell.metadata.ipub:
74 1
                    if hasattr(cell.metadata.ipub[key], "label"):
75 1
                        if cell.metadata.ipub[key]["label"] in captions:
76 1
                            logger.debug(
77
                                "replacing caption for: {}".format(
78
                                    cell.metadata.ipub[key]["label"]
79
                                )
80
                            )
81 1
                            cell.metadata.ipub[key]["caption"] = captions[
82
                                cell.metadata.ipub[key]["label"]
83
                            ]  # noqa: E501
84

85
                    # add float type/number prefix to caption, if required
86 1
                    if self.add_prefix:
87 1
                        if hasattr(cell.metadata.ipub[key], "caption"):
88 1
                            if hasattr(cell.metadata.ipub[key], "caption_prefix"):
89 1
                                newcaption = (
90
                                    cell.metadata.ipub[key].caption_prefix
91
                                    + cell.metadata.ipub[key].caption
92
                                )
93 1
                                cell.metadata.ipub[key].caption = newcaption
94

95 1
        return nb, resources

Read our documentation on viewing source code .

Loading