modm_data.pdf2html.ast

  1# Copyright 2022, Niklas Hauser
  2# SPDX-License-Identifier: MPL-2.0
  3
  4import logging
  5import anytree
  6from anytree import RenderTree, Node
  7from collections import defaultdict
  8from ..utils import Rectangle, ReversePreOrderIter
  9from .table import VirtualTable, Cell
 10
 11_LOGGER = logging.getLogger(__name__)
 12
 13
 14def _normalize_area(area: Node) -> Node:
 15    for child in ReversePreOrderIter(area):
 16        if child.name.startswith("list"):
 17            # We need to normalize the xpos back to the first character
 18            child.xpos = int(child.obj.bbox.left) - area.xpos
 19        else:
 20            # And then make the xpos relative to the area left for consistent comparisons
 21            child.xpos -= area.xpos
 22    area.xpos = 0
 23    return area
 24
 25
 26def merge_area(document: Node, area: Node, debug: bool = False) -> Node:
 27    if document is None:
 28        document = Node("document", xpos=0, _page=area.page, _doc=area.page.pdf, _end=None)
 29        document._end = document
 30    if not area.children:
 31        return document
 32    if debug:
 33        _LOGGER.debug()
 34
 35    def _find_end(node):
 36        # Find the last leaf node but skip lines, paragraphs, captions/tables/figures
 37        return next(
 38            (c for c in ReversePreOrderIter(node) if any(c.name.startswith(name) for name in {"head", "list", "note"})),
 39            next(ReversePreOrderIter(node), node),
 40        )
 41
 42    def _find_ancestor(filter_):
 43        if filter_(document._end):
 44            return document._end
 45        return next((c for c in document._end.iter_path_reverse() if filter_(c)), document.root)
 46
 47    area = _normalize_area(area)
 48    if debug:
 49        _LOGGER.debug(RenderTree(area))
 50    children = area.children
 51    # All area nodes up to the next top-level element must now be
 52    # xpos-aligned with the previous area's last leaf node
 53    connect_index = next((ii for ii, c in enumerate(children) if c.name.startswith("head")), len(children))
 54    x_em = area.page._spacing["x_em"]
 55
 56    if debug:
 57        _LOGGER.debug("area=", area, "connect_index=", connect_index)
 58    # Align these children with the last leaf node xpos
 59    for child in children[:connect_index]:
 60        if any(child.name.startswith(name) for name in {"list"}):
 61            # Find the node that is left of the current node but not too far left
 62            host = _find_ancestor(lambda c: -4 * x_em < (c.xpos - child.xpos) < -x_em or c.name.startswith("head"))
 63        elif (
 64            child.name == "para"
 65            and document._end.name == "note"
 66            and child.children[0].obj.contains_font("Italic", "Oblique")
 67        ):
 68            host = document._end
 69        else:
 70            # Insert underneath the next heading
 71            host = _find_ancestor(lambda c: c.name.startswith("head"))
 72
 73        child.parent = host
 74        document._end = _find_end(document)
 75        if debug:
 76            _LOGGER.debug(
 77                f"{child=}",
 78            )
 79            _LOGGER.debug(f"{host=}")
 80            _LOGGER.debug(f"end={document._end}")
 81            _LOGGER.debug()
 82
 83    # Add the remaining top-level children to connect index node
 84    if connect_index < len(children):
 85        children[connect_index].parent = document
 86        for child in children[connect_index + 1 :]:
 87            child.parent = children[connect_index]
 88
 89    document._end = _find_end(document)
 90
 91    if debug:
 92        _LOGGER.debug()
 93        _LOGGER.debug()
 94
 95    return document
 96
 97
 98def normalize_lists(node: Node) -> Node:
 99    lists = []
100    current = []
101    current_name = None
102    for child in node.children:
103        # Normalize the lists from the leaves up
104        normalize_lists(child)
105        # then split the children based on their names
106        if current_name is None or child.name == current_name:
107            current.append(child)
108        else:
109            lists.append(current)
110            current = [child]
111        current_name = child.name
112    if current:
113        lists.append(current)
114
115    # Create a new list of children
116    new_children = []
117    for llist in lists:
118        # Insert a new list group node and redirect all children to it
119        if llist[0].name.startswith("list"):
120            nlist = Node(llist[0].name, obj=llist[0].obj, start=llist[0].value, xpos=llist[0].xpos)
121            for lnode in llist:
122                lnode.name = "element"
123                lnode.parent = nlist
124
125            new_children.append(nlist)
126        else:
127            new_children.extend(llist)
128
129    # Set the new children which have the same order
130    node.children = new_children
131    return node
132
133
134def normalize_paragraphs(document: Node) -> Node:
135    paras = anytree.search.findall(document, filter_=lambda n: n.name == "para")
136    parents = set(p.parent for p in paras if p.parent.name in {"element", "caption", "document", "cell"})
137    for parent in parents:
138        # Replace the paragraph only if it's the *only* paragraph in this node
139        if parent.name in {"caption"} or sum(1 for p in parent.children if p.name == "para") == 1:
140            # Replace like this to preserve children order
141            parent.children = [p.children[0] if p.name == "para" else p for p in parent.children]
142            # Now we need to merge the text tags into the first one
143            texts = [p for p in parent.children if p.name == "text"]
144            if len(texts) > 1:
145                first_text = texts[0]
146                for text in texts[1:]:
147                    for line in text.children:
148                        line.parent = first_text
149                    text.parent = None
150    return document
151
152
153def normalize_toc(document: Node) -> Node:
154    """Joins the tables of contents of consecutive pages and the entries split across them."""
155    for toc in anytree.search.findall(document, filter_=lambda n: n.name == "toc"):
156        index = toc.parent.children.index(toc)
157        if not index or (previous := toc.parent.children[index - 1]).name != "toc":
158            continue
159        last, first = previous.children[-1], toc.children[0]
160        if last.target is None and first.marker is None:
161            last.title = f"{last.title} {first.title}".strip()
162            if last._chars and first._chars:
163                last._chars.append(last._chars[-1][:2] + (" ",))
164            last._chars += first._chars
165            last.target = first.target
166            # Keep the page marker
167            for child in first.children:
168                child.parent = last
169            first.parent = None
170        # Reassigning all children would detach and attach them all again for every page
171        for entry in toc.children:
172            entry.parent = previous
173        toc.parent = None
174    return document
175
176
177def normalize_lines(document: Node) -> Node:
178    paras = anytree.search.findall(document, filter_=lambda n: n.name == "para")
179    for para in paras:
180        text = Node("text")
181        for line in para.children:
182            line.parent = text
183        para.children = [text]
184    return document
185
186
187def normalize_captions(document: Node) -> Node:
188    captions = anytree.search.findall(document, filter_=lambda n: n.name == "caption")
189    for caption in captions:
190        cindex = caption.parent.children.index(caption)
191        # Find the next table for this caption within 5 nodes
192        for sibling in caption.parent.children[cindex : cindex + 6]:
193            if sibling.name == caption._type:
194                caption.parent = sibling
195                sibling.number = caption.number
196                break
197        else:
198            _LOGGER.error(f"Discarding caption {caption}!\n{RenderTree(caption)}")
199            caption.parent = None
200    return document
201
202
203def normalize_headings(document: Node) -> Node:
204    headings = anytree.search.findall(document, filter_=lambda n: n.name.startswith("head"))
205    for heading in headings:
206        para = heading.children[0]
207        if not para.children[0].children:
208            # Remove empty headers
209            para.parent = None
210        else:
211            # Rename paragraph to heading
212            para.__dict__["marker"] = heading.marker
213            para.name = heading.name
214        heading.name = "section"
215    return document
216
217
218def normalize_registers(document: Node) -> Node:
219    bits_list = []
220    sections = anytree.search.findall(document, filter_=lambda n: n.name == "section")
221    for section in sections + (document,):
222        new_children = []
223        bits = None
224        for child in section.children:
225            if child.name == "bit":
226                # Insert a new bits group node and redirect all children to it
227                if bits is None or bits._page != child._page:
228                    bits = Node("table", xpos=child.xpos, obj=None, _type="bits", _page=child._page)
229                    new_children.append(bits)
230                    bits_list.append(bits)
231                child.parent = bits
232            else:
233                bits = None
234                new_children.append(child)
235        # Set the new children which have the same order
236        section.children = new_children
237
238    # Reformat the bits nodes into tables
239    for bits in bits_list:
240        cells = []
241        for ypos, bit in enumerate(bits.children):
242            # The pages starting in a bit description now start at the table
243            for page in anytree.search.findall(bit, filter_=lambda n: n.name == "page"):
244                page.parent = bits
245            bit.parent = None
246            # The top is the first line, the bottom by the last line
247            top = next(c.obj.bbox.top for c in bit.descendants if c.name == "line")
248            bottom = next(c.obj.bbox.bottom for c in reversed(bit.descendants) if c.name == "line")
249            # Left table cell contains Bits
250            left_bbox = Rectangle(bit._left, bottom, bit._middle, top)
251            cells.append(Cell(None, (ypos, 0), left_bbox, (1, 1, 1, 1), is_simple=True))
252            # Right cell contains description
253            right_bbox = Rectangle(bit._middle, bottom, bit._right, top)
254            cells.append(Cell(None, (ypos, 1), right_bbox, (1, 1, 1, 1)))
255        tbbox = Rectangle(
256            min(c.bbox.left for c in cells),
257            min(c.bbox.bottom for c in cells),
258            max(c.bbox.right for c in cells),
259            max(c.bbox.top for c in cells),
260        )
261        bits.obj = VirtualTable(bits._page, tbbox, cells, "bitfield")
262
263    return document
264
265
266def _remove_merged(table: Node, merged: Node):
267    # The pages starting in the merged table now start at the table
268    for page in anytree.search.findall(merged, filter_=lambda n: n.name == "page"):
269        page.parent = table
270    merged.parent = None
271
272
273def normalize_tables(document: Node) -> Node:
274    content_tables = defaultdict(list)
275    register_tables = []
276    bits_tables = []
277    current_rtables = []
278    current_bitstables = []
279
280    def _push():
281        nonlocal current_rtables, register_tables
282        nonlocal current_bitstables, bits_tables
283        if current_rtables:
284            register_tables.append(current_rtables)
285            current_rtables = []
286        if current_bitstables:
287            bits_tables.append(current_bitstables)
288            current_bitstables = []
289
290    sections = anytree.search.findall(document, filter_=lambda n: n.name == "section")
291    last_number = 0
292    for section in sections + (document,):
293        current_rtables = []
294        current_bitstables = []
295        for child in section.children:
296            if child.name == "table":
297                if child._type == "table":
298                    if child.number > 0:
299                        # Collect tables with the same number together
300                        content_tables[child.number].append(child)
301                        if document._page._template == "blue_gray":
302                            last_number = child.number
303                    elif last_number > 0:
304                        # Tables without caption may follow
305                        content_tables[last_number].append(child)
306                    _push()
307                elif child._type == "register":
308                    # Collect register tables that follow each other directly
309                    current_rtables.append(child)
310                elif child._type == "bits":
311                    # Collect bits tables that follow each other directly
312                    current_bitstables.append(child)
313                else:
314                    last_number = 0
315            else:
316                _push()
317                last_number = 0
318        _push()
319        last_number = 0
320    _push()
321
322    # Merge all tables of the same number by appending at the bottom
323    for number, tables in content_tables.items():
324        for table in tables[1:]:
325            print(f"T{table.obj._page.number} ", end="")
326            if tables[0].obj.append_bottom(table.obj):
327                _remove_merged(tables[0], table)
328    # Merge all register tables by appending to the right
329    for tables in register_tables:
330        for table in tables[1:]:
331            if tables[0].obj.append_side(table.obj, expand=True):
332                _remove_merged(tables[0], table)
333    # Merge all bits tables by appending at the bottom
334    for tables in bits_tables:
335        for table in tables[1:]:
336            if tables[0].obj.append_bottom(table.obj, merge_headers=False):
337                _remove_merged(tables[0], table)
338
339    return document
340
341
342def normalize_chapters(document: Node) -> Node:
343    headings = anytree.search.findall(document, filter_=lambda n: n.name in ["head1", "head2"], maxlevel=3)
344    idxs = [document.children.index(h.parent) for h in headings] + [len(document.children)]
345    if idxs[0] != 0:
346        idxs = [0] + idxs
347    if idxs[-1] != len(document.children):
348        idxs += [len(document.children)]
349
350    cleaner = str.maketrans(" /()-,:", "_______")
351
352    chapters = []
353    for idx0, idx1 in zip(idxs, idxs[1:]):
354        # Find the chapter name
355        heading = document.children[idx0].children[0]
356        lines = anytree.search.findall(heading, filter_=lambda n: n.name == "line")
357        chapter_name = ("".join(c.char for c in line.obj.chars).strip() for line in lines)
358        chapter_name = " ".join(chapter_name)
359        if heading.name == "head1":
360            chapter_name = "0 " + chapter_name
361        filename = chapter_name.lower().translate(cleaner)
362        chapters.append((chapter_name, filename, document.children[idx0 : idx1 + 1]))
363
364    for title, filename, nodes in chapters:
365        chapter = Node("chapter", title=title, _filename=filename, parent=document)
366        for node in nodes:
367            node.parent = chapter
368
369    return document
def merge_area( document: anytree.node.node.Node, area: anytree.node.node.Node, debug: bool = False) -> anytree.node.node.Node:
27def merge_area(document: Node, area: Node, debug: bool = False) -> Node:
28    if document is None:
29        document = Node("document", xpos=0, _page=area.page, _doc=area.page.pdf, _end=None)
30        document._end = document
31    if not area.children:
32        return document
33    if debug:
34        _LOGGER.debug()
35
36    def _find_end(node):
37        # Find the last leaf node but skip lines, paragraphs, captions/tables/figures
38        return next(
39            (c for c in ReversePreOrderIter(node) if any(c.name.startswith(name) for name in {"head", "list", "note"})),
40            next(ReversePreOrderIter(node), node),
41        )
42
43    def _find_ancestor(filter_):
44        if filter_(document._end):
45            return document._end
46        return next((c for c in document._end.iter_path_reverse() if filter_(c)), document.root)
47
48    area = _normalize_area(area)
49    if debug:
50        _LOGGER.debug(RenderTree(area))
51    children = area.children
52    # All area nodes up to the next top-level element must now be
53    # xpos-aligned with the previous area's last leaf node
54    connect_index = next((ii for ii, c in enumerate(children) if c.name.startswith("head")), len(children))
55    x_em = area.page._spacing["x_em"]
56
57    if debug:
58        _LOGGER.debug("area=", area, "connect_index=", connect_index)
59    # Align these children with the last leaf node xpos
60    for child in children[:connect_index]:
61        if any(child.name.startswith(name) for name in {"list"}):
62            # Find the node that is left of the current node but not too far left
63            host = _find_ancestor(lambda c: -4 * x_em < (c.xpos - child.xpos) < -x_em or c.name.startswith("head"))
64        elif (
65            child.name == "para"
66            and document._end.name == "note"
67            and child.children[0].obj.contains_font("Italic", "Oblique")
68        ):
69            host = document._end
70        else:
71            # Insert underneath the next heading
72            host = _find_ancestor(lambda c: c.name.startswith("head"))
73
74        child.parent = host
75        document._end = _find_end(document)
76        if debug:
77            _LOGGER.debug(
78                f"{child=}",
79            )
80            _LOGGER.debug(f"{host=}")
81            _LOGGER.debug(f"end={document._end}")
82            _LOGGER.debug()
83
84    # Add the remaining top-level children to connect index node
85    if connect_index < len(children):
86        children[connect_index].parent = document
87        for child in children[connect_index + 1 :]:
88            child.parent = children[connect_index]
89
90    document._end = _find_end(document)
91
92    if debug:
93        _LOGGER.debug()
94        _LOGGER.debug()
95
96    return document
def normalize_lists(node: anytree.node.node.Node) -> anytree.node.node.Node:
 99def normalize_lists(node: Node) -> Node:
100    lists = []
101    current = []
102    current_name = None
103    for child in node.children:
104        # Normalize the lists from the leaves up
105        normalize_lists(child)
106        # then split the children based on their names
107        if current_name is None or child.name == current_name:
108            current.append(child)
109        else:
110            lists.append(current)
111            current = [child]
112        current_name = child.name
113    if current:
114        lists.append(current)
115
116    # Create a new list of children
117    new_children = []
118    for llist in lists:
119        # Insert a new list group node and redirect all children to it
120        if llist[0].name.startswith("list"):
121            nlist = Node(llist[0].name, obj=llist[0].obj, start=llist[0].value, xpos=llist[0].xpos)
122            for lnode in llist:
123                lnode.name = "element"
124                lnode.parent = nlist
125
126            new_children.append(nlist)
127        else:
128            new_children.extend(llist)
129
130    # Set the new children which have the same order
131    node.children = new_children
132    return node
def normalize_paragraphs(document: anytree.node.node.Node) -> anytree.node.node.Node:
135def normalize_paragraphs(document: Node) -> Node:
136    paras = anytree.search.findall(document, filter_=lambda n: n.name == "para")
137    parents = set(p.parent for p in paras if p.parent.name in {"element", "caption", "document", "cell"})
138    for parent in parents:
139        # Replace the paragraph only if it's the *only* paragraph in this node
140        if parent.name in {"caption"} or sum(1 for p in parent.children if p.name == "para") == 1:
141            # Replace like this to preserve children order
142            parent.children = [p.children[0] if p.name == "para" else p for p in parent.children]
143            # Now we need to merge the text tags into the first one
144            texts = [p for p in parent.children if p.name == "text"]
145            if len(texts) > 1:
146                first_text = texts[0]
147                for text in texts[1:]:
148                    for line in text.children:
149                        line.parent = first_text
150                    text.parent = None
151    return document
def normalize_toc(document: anytree.node.node.Node) -> anytree.node.node.Node:
154def normalize_toc(document: Node) -> Node:
155    """Joins the tables of contents of consecutive pages and the entries split across them."""
156    for toc in anytree.search.findall(document, filter_=lambda n: n.name == "toc"):
157        index = toc.parent.children.index(toc)
158        if not index or (previous := toc.parent.children[index - 1]).name != "toc":
159            continue
160        last, first = previous.children[-1], toc.children[0]
161        if last.target is None and first.marker is None:
162            last.title = f"{last.title} {first.title}".strip()
163            if last._chars and first._chars:
164                last._chars.append(last._chars[-1][:2] + (" ",))
165            last._chars += first._chars
166            last.target = first.target
167            # Keep the page marker
168            for child in first.children:
169                child.parent = last
170            first.parent = None
171        # Reassigning all children would detach and attach them all again for every page
172        for entry in toc.children:
173            entry.parent = previous
174        toc.parent = None
175    return document

Joins the tables of contents of consecutive pages and the entries split across them.

def normalize_lines(document: anytree.node.node.Node) -> anytree.node.node.Node:
178def normalize_lines(document: Node) -> Node:
179    paras = anytree.search.findall(document, filter_=lambda n: n.name == "para")
180    for para in paras:
181        text = Node("text")
182        for line in para.children:
183            line.parent = text
184        para.children = [text]
185    return document
def normalize_captions(document: anytree.node.node.Node) -> anytree.node.node.Node:
188def normalize_captions(document: Node) -> Node:
189    captions = anytree.search.findall(document, filter_=lambda n: n.name == "caption")
190    for caption in captions:
191        cindex = caption.parent.children.index(caption)
192        # Find the next table for this caption within 5 nodes
193        for sibling in caption.parent.children[cindex : cindex + 6]:
194            if sibling.name == caption._type:
195                caption.parent = sibling
196                sibling.number = caption.number
197                break
198        else:
199            _LOGGER.error(f"Discarding caption {caption}!\n{RenderTree(caption)}")
200            caption.parent = None
201    return document
def normalize_headings(document: anytree.node.node.Node) -> anytree.node.node.Node:
204def normalize_headings(document: Node) -> Node:
205    headings = anytree.search.findall(document, filter_=lambda n: n.name.startswith("head"))
206    for heading in headings:
207        para = heading.children[0]
208        if not para.children[0].children:
209            # Remove empty headers
210            para.parent = None
211        else:
212            # Rename paragraph to heading
213            para.__dict__["marker"] = heading.marker
214            para.name = heading.name
215        heading.name = "section"
216    return document
def normalize_registers(document: anytree.node.node.Node) -> anytree.node.node.Node:
219def normalize_registers(document: Node) -> Node:
220    bits_list = []
221    sections = anytree.search.findall(document, filter_=lambda n: n.name == "section")
222    for section in sections + (document,):
223        new_children = []
224        bits = None
225        for child in section.children:
226            if child.name == "bit":
227                # Insert a new bits group node and redirect all children to it
228                if bits is None or bits._page != child._page:
229                    bits = Node("table", xpos=child.xpos, obj=None, _type="bits", _page=child._page)
230                    new_children.append(bits)
231                    bits_list.append(bits)
232                child.parent = bits
233            else:
234                bits = None
235                new_children.append(child)
236        # Set the new children which have the same order
237        section.children = new_children
238
239    # Reformat the bits nodes into tables
240    for bits in bits_list:
241        cells = []
242        for ypos, bit in enumerate(bits.children):
243            # The pages starting in a bit description now start at the table
244            for page in anytree.search.findall(bit, filter_=lambda n: n.name == "page"):
245                page.parent = bits
246            bit.parent = None
247            # The top is the first line, the bottom by the last line
248            top = next(c.obj.bbox.top for c in bit.descendants if c.name == "line")
249            bottom = next(c.obj.bbox.bottom for c in reversed(bit.descendants) if c.name == "line")
250            # Left table cell contains Bits
251            left_bbox = Rectangle(bit._left, bottom, bit._middle, top)
252            cells.append(Cell(None, (ypos, 0), left_bbox, (1, 1, 1, 1), is_simple=True))
253            # Right cell contains description
254            right_bbox = Rectangle(bit._middle, bottom, bit._right, top)
255            cells.append(Cell(None, (ypos, 1), right_bbox, (1, 1, 1, 1)))
256        tbbox = Rectangle(
257            min(c.bbox.left for c in cells),
258            min(c.bbox.bottom for c in cells),
259            max(c.bbox.right for c in cells),
260            max(c.bbox.top for c in cells),
261        )
262        bits.obj = VirtualTable(bits._page, tbbox, cells, "bitfield")
263
264    return document
def normalize_tables(document: anytree.node.node.Node) -> anytree.node.node.Node:
274def normalize_tables(document: Node) -> Node:
275    content_tables = defaultdict(list)
276    register_tables = []
277    bits_tables = []
278    current_rtables = []
279    current_bitstables = []
280
281    def _push():
282        nonlocal current_rtables, register_tables
283        nonlocal current_bitstables, bits_tables
284        if current_rtables:
285            register_tables.append(current_rtables)
286            current_rtables = []
287        if current_bitstables:
288            bits_tables.append(current_bitstables)
289            current_bitstables = []
290
291    sections = anytree.search.findall(document, filter_=lambda n: n.name == "section")
292    last_number = 0
293    for section in sections + (document,):
294        current_rtables = []
295        current_bitstables = []
296        for child in section.children:
297            if child.name == "table":
298                if child._type == "table":
299                    if child.number > 0:
300                        # Collect tables with the same number together
301                        content_tables[child.number].append(child)
302                        if document._page._template == "blue_gray":
303                            last_number = child.number
304                    elif last_number > 0:
305                        # Tables without caption may follow
306                        content_tables[last_number].append(child)
307                    _push()
308                elif child._type == "register":
309                    # Collect register tables that follow each other directly
310                    current_rtables.append(child)
311                elif child._type == "bits":
312                    # Collect bits tables that follow each other directly
313                    current_bitstables.append(child)
314                else:
315                    last_number = 0
316            else:
317                _push()
318                last_number = 0
319        _push()
320        last_number = 0
321    _push()
322
323    # Merge all tables of the same number by appending at the bottom
324    for number, tables in content_tables.items():
325        for table in tables[1:]:
326            print(f"T{table.obj._page.number} ", end="")
327            if tables[0].obj.append_bottom(table.obj):
328                _remove_merged(tables[0], table)
329    # Merge all register tables by appending to the right
330    for tables in register_tables:
331        for table in tables[1:]:
332            if tables[0].obj.append_side(table.obj, expand=True):
333                _remove_merged(tables[0], table)
334    # Merge all bits tables by appending at the bottom
335    for tables in bits_tables:
336        for table in tables[1:]:
337            if tables[0].obj.append_bottom(table.obj, merge_headers=False):
338                _remove_merged(tables[0], table)
339
340    return document
def normalize_chapters(document: anytree.node.node.Node) -> anytree.node.node.Node:
343def normalize_chapters(document: Node) -> Node:
344    headings = anytree.search.findall(document, filter_=lambda n: n.name in ["head1", "head2"], maxlevel=3)
345    idxs = [document.children.index(h.parent) for h in headings] + [len(document.children)]
346    if idxs[0] != 0:
347        idxs = [0] + idxs
348    if idxs[-1] != len(document.children):
349        idxs += [len(document.children)]
350
351    cleaner = str.maketrans(" /()-,:", "_______")
352
353    chapters = []
354    for idx0, idx1 in zip(idxs, idxs[1:]):
355        # Find the chapter name
356        heading = document.children[idx0].children[0]
357        lines = anytree.search.findall(heading, filter_=lambda n: n.name == "line")
358        chapter_name = ("".join(c.char for c in line.obj.chars).strip() for line in lines)
359        chapter_name = " ".join(chapter_name)
360        if heading.name == "head1":
361            chapter_name = "0 " + chapter_name
362        filename = chapter_name.lower().translate(cleaner)
363        chapters.append((chapter_name, filename, document.children[idx0 : idx1 + 1]))
364
365    for title, filename, nodes in chapters:
366        chapter = Node("chapter", title=title, _filename=filename, parent=document)
367        for node in nodes:
368            node.parent = chapter
369
370    return document