modm_data.pdf2html.table

  1# Copyright 2022, Niklas Hauser
  2# SPDX-License-Identifier: MPL-2.0
  3
  4import logging
  5import statistics
  6from functools import cached_property
  7from collections import defaultdict
  8from ..utils import HLine, VLine, Rectangle
  9from .cell import Cell, Borders
 10
 11_LOGGER = logging.getLogger(__name__)
 12
 13
 14class Table:
 15    def __init__(
 16        self, page, bbox: Rectangle, xlines: list, ylines: list, cbbox: Rectangle = None, is_register: bool = False
 17    ):
 18        self._page = page
 19        self._spacing = page._spacing
 20        self.bbox = bbox
 21        self.cbbox = None if is_register else cbbox
 22        self._type = "table"
 23        self._bit_headers = None
 24
 25        if not is_register:
 26            # Overlines of negated values are horizontal lines inside a cell that end on the glyphs below them.
 27            # A cell border ends at a vertical line, or on nothing when the table is missing a border.
 28            def _touches(x, y):
 29                if abs(x - bbox.left) < 1 or abs(x - bbox.right) < 1:
 30                    return True
 31                return any(abs(x - v.p0.x) < 1 and v.p0.y - 1 < y < v.p1.y + 1 for v in xlines)
 32
 33            def _is_overline(line):
 34                if _touches(line.p0.x, line.p0.y) or _touches(line.p1.x, line.p0.y):
 35                    return False
 36                return any(
 37                    # an overline drawn in pieces is joined, its pieces lie inside it
 38                    o.left - 1 < line.p0.x and line.p1.x < o.right + 1 and o.bottom - 1 < line.p0.y < o.top + 1
 39                    for o in page._overlines
 40                )
 41
 42            ylines = [line for line in ylines if not _is_overline(line)]
 43
 44        # Coalesce the vertical lines to detect the grid
 45        def _cluster(lines, key):
 46            atol = min(self._spacing["y_em"], self._spacing["x_em"]) / 4
 47            grid = defaultdict(list)
 48            last = -1e9
 49            current = -1e9
 50            for line in sorted(lines, key=key):
 51                if (last + atol) < key(line):
 52                    current = key(line)
 53                grid[current].append(line)
 54                last = key(line)
 55            return grid
 56
 57        xgrid = _cluster(xlines, lambda line: line.p0.x)
 58        ygrid = _cluster(ylines, lambda line: line.p0.y)
 59
 60        if is_register:
 61            self._type = "register"
 62
 63            # Find the positions of the top numbers
 64            clusters = []
 65            if lines := self._page.charlines_in_area(cbbox):
 66                if len(cluster := lines[0].clusters(self._page._spacing["x_em"] / 2)):
 67                    clusters.append((cluster, cbbox))
 68                else:
 69                    self.grid = (0, 0)
 70                    _LOGGER.error(f"Cannot find any bit position clusters! {self} ({self._page})")
 71
 72            # Find the positions of the second row of numbers
 73            if len(ygrid) > 2:
 74                for yi, (ypos0, ypos1) in enumerate(zip(sorted(ygrid), sorted(ygrid)[1:])):
 75                    nbbox = Rectangle(self.bbox.left, ygrid[ypos0][0].p0.y, self.bbox.right, ygrid[ypos1][0].p0.y)
 76                    if lines := self._page.charlines_in_area(nbbox):
 77                        if all(c.char.isnumeric() or c.unicode in {0x20, 0xA, 0xD} for c in lines[0].chars):
 78                            if not len(cluster := lines[0].clusters(self._page._spacing["x_em"] / 2)) % 16:
 79                                clusters.append((cluster, nbbox))
 80                                self._bit_headers = len(ygrid) - yi - 1
 81                            else:
 82                                self.grid = (len(cluster), 0)
 83                                _LOGGER.warning(
 84                                    f"Second bit pattern does not have 16 or 32 clusters! {self} ({self._page})"
 85                                )
 86                            break
 87
 88            # Merge these clusters to find their positions
 89            for cluster, bbox in clusters:
 90                # Close left and right side
 91                xgrid[sorted(xgrid)[0]].append(VLine(self.bbox.left, bbox.bottom, bbox.top))
 92                xgrid[sorted(xgrid)[-1]].append(VLine(self.bbox.right, bbox.bottom, bbox.top))
 93                # Now close the lines in between
 94                for cleft, cright in zip(cluster, cluster[1:]):
 95                    # find a line between the clusters
 96                    xpos = next(
 97                        (
 98                            (x, xgrid[x][0].p0.x)
 99                            for x in sorted(xgrid)
100                            if cleft.bbox.right < xgrid[x][0].p0.x < cright.bbox.left
101                        ),
102                        None,
103                    )
104                    # Didn't find one, we must add one manually
105                    if xpos is None:
106                        xpos = (cleft.bbox.right + cright.bbox.left) / 2
107                        xpos = (int(round(xpos)), xpos)
108                    # Add it to the grid
109                    xgrid[xpos[0]].append(VLine(xpos[1], bbox.bottom, bbox.top))
110            # close the top
111            ygrid[self.bbox.top].append(HLine(self.bbox.top, self.bbox.left, self.bbox.right))
112
113        # Fix the position keys properly
114        self._xgrid = {int(round(statistics.fmean(m.p0.x for m in line))): line for line in xgrid.values()}
115        self._ygrid = {int(round(statistics.fmean(m.p0.y for m in line))): line for line in ygrid.values()}
116        # Map the positions to integers
117        self._xpos = list(sorted(self._xgrid))
118        self._ypos = list(sorted(self._ygrid))
119
120        self.grid = (len(self._xpos) - 1, len(self._ypos) - 1)
121        self._cells = None
122
123    def _cell_borders(self, x: int, y: int, bbox: Rectangle, mask: int = 0b1111) -> tuple[int, int, int, int]:
124        # left, bottom, right, top
125        borders = [0, 0, 0, 0]
126        mp = bbox.midpoint
127        if mask & 0b1000:  # Left
128            for line in self._xgrid[self._xpos[x]]:
129                if line.p0.y < mp.y < line.p1.y:
130                    borders[0] = line.width
131                    assert line.width
132                    break
133        if mask & 0b0010:  # Right
134            for line in self._xgrid[self._xpos[x + 1]]:
135                if line.p0.y < mp.y < line.p1.y:
136                    borders[2] = line.width
137                    assert line.width
138                    break
139        if mask & 0b0100:  # Bottom
140            for line in self._ygrid[self._ypos[y]]:
141                if line.p0.x < mp.x < line.p1.x:
142                    borders[1] = line.width
143                    assert line.width
144                    break
145        if mask & 0b0001:  # Top
146            for line in self._ygrid[self._ypos[y + 1]]:
147                if line.p0.x < mp.x < line.p1.x:
148                    borders[3] = line.width
149                    assert line.width
150                    break
151
152        return Borders(*borders)
153
154    def _fix_borders(self, cells, x: int, y: int):
155        # We are looking at the 9 neighbors around the cells
156        c = cells[(x, y)].borders
157        r = cells[(x + 1, y)].borders if cells[(x + 1, y)] is not None else Borders(0, 0, 1, 0)
158        t = cells[(x, y + 1)].borders if cells[(x, y + 1)] is not None else Borders(0, 1, 0, 0)
159
160        # if (not c.top and c.left and c.right and c.bottom) and "Reset value" in cell.content:
161        #     c.top = 1
162
163        # Open at the top into a span
164        if (not c.top and c.right) and (not t.right or not t.left):
165            c.top = 1
166            t.bottom = 1
167        # Open at the top and self is a span
168        if (not c.top and not c.right) and (t.right and t.left):
169            c.top = 1
170            t.bottom = 1
171
172        # Open to the right into a span
173        if (not c.right and c.top) and (not r.top or not r.bottom):
174            c.right = 1
175            r.left = 1
176        # Open to the right and self is a span
177        if (not c.right and not c.top) and (r.top and r.bottom):
178            c.right = 1
179            r.left = 1
180
181    @property
182    def cells(self) -> list[Cell]:
183        if self._cells is None:
184            if self.grid < (1, 1):
185                self._cells = []
186                return self._cells
187
188            # First determine the spans of cells by checking the borders
189            cells = defaultdict(lambda: None)
190            for yi, (y0, y1) in enumerate(zip(self._ypos, self._ypos[1:])):
191                for xi, (x0, x1) in enumerate(zip(self._xpos, self._xpos[1:])):
192                    bbox = Rectangle(x0, y0, x1, y1)
193                    borders = self._cell_borders(xi, yi, bbox, 0b1111)
194                    cells[(xi, yi)] = Cell(self, (self.grid[1] - 1 - yi, xi), bbox, borders, self._type == "register")
195
196            # Fix table cell borders via consistency checks
197            for yi in range(self.grid[1]):
198                for xi in range(self.grid[0]):
199                    self._fix_borders(cells, xi, yi)
200
201            # Merge the cells recursively
202            def _merge(px, py, x, y):
203                if cells[(x, y)] is None:
204                    return
205                # print(cells[(x, y)])
206                # Right border is open
207                if not cells[(x, y)].borders.right:
208                    if cells[(x + 1, y)] is not None:
209                        cells[(px, py)]._merge(cells[(x + 1, y)])
210                        _merge(px, py, x + 1, y)
211                        cells[(x + 1, y)] = None
212                # Top border is open
213                if not cells[(x, y)].borders.top:
214                    if cells[(x, y + 1)] is not None:
215                        cells[(px, py)]._merge(cells[(x, y + 1)])
216                        _merge(px, py, x, y + 1)
217                        cells[(x, y + 1)] = None
218
219            # Start merging in bottom left cell
220            for yi in range(self.grid[1]):
221                for xi in range(self.grid[0]):
222                    _merge(xi, yi, xi, yi)
223
224            # Find the header line, it is thicker than normal
225            y_header_pos = self.grid[1]
226            if self._type != "register":
227                if self.grid[1] > 1:
228                    line_widths = {
229                        round(line.width, 1) for llist in self._ygrid.values() for line in llist if line.width != 0.1
230                    }  # magic width of virtual borders
231                    if line_widths:
232                        line_width_max = max(line_widths) * 0.9
233                        if min(line_widths) < line_width_max:
234                            # Find the first thick line starting from the top
235                            y_header_pos = next(
236                                (
237                                    yi
238                                    for yi, ypos in reversed(list(enumerate(self._ypos)))
239                                    if any(line.width > line_width_max for line in self._ygrid[ypos])
240                                ),
241                                y_header_pos,
242                            )
243
244                # Map all the header
245                is_bold = []
246                for yi in range(0 if y_header_pos == self.grid[1] else y_header_pos, self.grid[1]):
247                    bbox = None
248                    for xi in range(self.grid[0]):
249                        if (cell := cells[(xi, yi)]) is not None:
250                            if bbox is None:
251                                bbox = cell.bbox
252                            else:
253                                bbox = bbox.joined(cell.bbox)
254                    if bbox is None:
255                        continue
256                    chars = self._page.chars_in_area(bbox)
257                    is_bold_pct = sum(1 if "Bold" in c.font else 0 for c in chars) / len(chars) if chars else 1
258                    is_bold.append((yi, is_bold_pct > self._spacing["th"]))
259
260                # Some tables have no bold cells at all
261                if all(not b[1] for b in is_bold):
262                    # Special case for two row tables without bold headers, but a bold line inbetween
263                    if self.grid[1] == 2 and y_header_pos == 1:
264                        y_header_pos = 2
265                else:
266                    if y_header_pos < self.grid[1]:
267                        # Find the lowest bold row starting from bold line
268                        y_header_pos = next((b[0] for b in is_bold if y_header_pos <= b[0] and b[1]), y_header_pos)
269                    else:
270                        # Find the lowest bold row starting from the top
271                        for b in reversed(is_bold):
272                            if not b[1]:
273                                break
274                            y_header_pos = b[0]
275
276            # Tell the header cells
277            for yi in range(y_header_pos, self.grid[1]):
278                for xi in range(self.grid[0]):
279                    if (cell := cells[(xi, yi)]) is not None:
280                        cell.is_header = True
281
282            # Flatten into array
283            cells = [c for c in cells.values() if c is not None]
284
285            # Normalize cells for registers by moving the lower ones right and up
286            if self._type == "register" and self._bit_headers is not None:
287                for cell in cells:
288                    if cell.y >= self._bit_headers:
289                        cell._move(16, -self._bit_headers)
290                    elif self._bit_headers <= 2 and cell.y == self._bit_headers - 1:
291                        cell._expand(0, 3 - self._bit_headers)
292                self.grid = (32, 4)
293
294            self._cells = list(sorted(cells, key=lambda c: c.positions[0]))
295
296        return self._cells
297
298    def append_bottom(self, other, merge_headers=True) -> bool:
299        debug = False
300        xgrid = self.grid[0]
301        if merge_headers and xgrid != other.grid[0]:
302            # Some tables have different column layouts due to span cells
303            # So we must correct the X positions of all cells accordingly
304            self_xheaders = defaultdict(set)
305            other_xheaders = defaultdict(set)
306            self_headers = [c for c in self.cells if c.is_header]
307            other_headers = [c for c in other.cells if c.is_header]
308            # Find the smallest set of spanning xpositions based on the header cells
309            for xpos in range(self.grid[0]):
310                for hcell in self_headers:
311                    if any(p[1] == xpos for p in hcell.positions):
312                        self_xheaders[hcell.x].add(xpos)
313            for xpos in range(other.grid[0]):
314                for hcell in other_headers:
315                    if any(p[1] == xpos for p in hcell.positions):
316                        other_xheaders[hcell.x].add(xpos)
317
318            # Compute the shared
319            self_heads = sorted(self_xheaders.keys())
320            other_heads = sorted(other_xheaders.keys())
321            xgrid = 0
322            merged_xheaders = defaultdict(set)
323            # Zip the groups together, these represent the matching header group spans
324            for self_xhead, other_xhead in zip(self_heads, other_heads):
325                size = max(len(self_xheaders[self_xhead]), len(other_xheaders[other_xhead]))
326                merged_xheaders[max(self_xhead, other_xhead)] = set(range(xgrid, xgrid + size))
327                xgrid += size
328
329            if debug:
330                print(len(self_xheaders), self_xheaders)
331                print(len(other_xheaders), other_xheaders)
332                print(len(merged_xheaders), merged_xheaders)
333            # If they are not equal length the table layouts are not compatible at all!
334            if len(self_heads) != len(other_heads):
335                _LOGGER.error(f"Failure to append table {other} ({other._page}) onto table {self} ({self._page})")
336                return False
337
338            # We want to stuff/move the cell positions inplace, therefore we start
339            # backwards moving the high numbers even higher, so that we don't
340            # overwrite ourselves and get stuck in an infinite loop
341            # Zip the groups together, these represent the matching header group spans
342            for self_xhead, other_xhead in zip(reversed(self_heads), reversed(other_heads)):
343                merged_xhead = max(self_xhead, other_xhead)
344                self_xpos = sorted(self_xheaders[self_xhead], reverse=True)
345                other_xpos = sorted(other_xheaders[other_xhead], reverse=True)
346                merged_xpos = sorted(merged_xheaders[merged_xhead], reverse=True)
347
348                def _insert_cells(cell, src, dsts, insert_only):
349                    assert dsts
350                    new_positions = []
351                    any_change = False
352                    for cpos in reversed(cell.positions):
353                        if insert_only:
354                            # If our set is empty we must only insert positions
355                            if cpos[1] == src:
356                                for xpos in dsts:
357                                    if debug:
358                                        print(f"Insert {cpos}++{(cpos[0], xpos)}")
359                                    new_positions.append((cpos[0], xpos))
360                                    any_change = True
361                            new_positions.append(cpos)
362                        else:
363                            # We must move (=replace and add) the span positions
364                            if cpos[1] == src:
365                                if debug:
366                                    print(f"Move {cpos}->{(cpos[0], dsts[0])}")
367                                new_positions.append((cpos[0], dsts[0]))
368                                any_change = True
369                            else:
370                                new_positions.append(cpos)
371                    if debug and any_change:
372                        print(f"{cell}: {src}->{dsts} {'I' if insert_only else 'M'}")
373                        print("old=", cell.positions, "new=", sorted(new_positions))
374                        print()
375                    assert new_positions
376                    assert len(new_positions) == len(set(new_positions))
377                    cell.positions = sorted(new_positions)
378                    cell._invalidate()
379
380                def _move_cells(cells, own_xpos):
381                    if debug:
382                        print()
383                        print(f"====== Rewrite rows: {own_xpos}->{merged_xpos} ======")
384                        print()
385
386                    for ii in range(max(len(own_xpos), len(merged_xpos))):
387                        insert_only = ii >= len(own_xpos)
388                        if insert_only:
389                            src = merged_xpos[ii - 1]
390                            dsts = merged_xpos[ii:]
391                            if debug:
392                                print(f"{src}->{dsts} I")
393                            for cell in cells:
394                                _insert_cells(cell, src, dsts, True)
395                            break
396                        else:
397                            src = own_xpos[ii]
398                            dsts = merged_xpos[ii : ii + 1]
399                            if debug:
400                                print(f"{src}->{dsts} M")
401                            for cell in cells:
402                                _insert_cells(cell, src, dsts, False)
403
404                if debug:
405                    print()
406                if self_xpos != merged_xpos:
407                    if debug:
408                        print(f"====== Self:  x={self_xhead}->{merged_xhead} xpos={self_xpos}->{merged_xpos}")
409                    _move_cells(self.cells, self_xpos)
410                if other_xpos != merged_xpos:
411                    if debug:
412                        print(
413                            f"====== Other: x={other_xhead}->{merged_xhead} xpos={other_xheaders[other_xhead]}->{merged_xheaders[merged_xhead]}"
414                        )
415                    _move_cells(other.cells, other_xpos)
416            if debug:
417                print()
418                print()
419                print()
420
421        # We must move the cells downwards now, but minus the header rows
422        rows = self.grid[1] - other.header_rows
423        for cell in other.cells:
424            # Discard the header cells, we just assume they are the same
425            if not cell.is_header:
426                cell._move(0, rows)
427                self.cells.append(cell)
428        self.cells.sort(key=lambda c: c.positions[0])
429        self.grid = (xgrid, other.grid[1] + rows)
430        if debug:
431            print(f"{self._page} -> {self.grid}")
432        return True
433
434    def append_side(self, other, expand=False) -> bool:
435        if self.grid[1] != other.grid[1]:
436            if expand:
437                _LOGGER.debug(
438                    f"Expanding bottom cells to match height: {self} ({self._page}) + {other} ({other._page})"
439                )
440                ymin = min(self.grid[1], other.grid[1])
441                ymax = max(self.grid[1], other.grid[1])
442                etable = other if self.grid[1] > other.grid[1] else self
443                for cell in etable.cells:
444                    if any(p[0] == ymin - 1 for p in cell.positions):
445                        cell._expand(0, ymax - ymin)
446                etable.grid = (etable.grid[0], ymax)
447            else:
448                _LOGGER.error(f"Unable to append table at side: {self} ({self._page}) + {other} ({other._page})")
449                return False
450
451        # We must move all cells to the right now
452        columns = self.grid[0]
453        for cell in other.cells:
454            cell._move(columns, 0)
455            self.cells.append(cell)
456        self.cells.sort(key=lambda c: c.positions[0])
457        self.grid = (other.grid[0] + columns, max(self.grid[1], other.grid[1]))
458        return True
459
460    @cached_property
461    def header_rows(self) -> int:
462        header_cells = [c for c in self.cells if c.is_header]
463        if header_cells:
464            return max(c.positions[-1][0] + 1 for c in header_cells)
465        return 0
466
467    def __repr__(self) -> str:
468        return f"Table({self.grid[0]}x{self.grid[1]})"
469
470
471class VirtualTable(Table):
472    def __init__(self, page, bbox, cells, table_type=None):
473        self._page = page
474        self._spacing = page._spacing
475        self._type = table_type or "virtual"
476        self.bbox = bbox
477        self._cells = cells
478        self.grid = (max(c.x for c in cells) + 1, max(c.y for c in cells) + 1)
479        for cell in cells:
480            cell._table = self
481
482    def __repr__(self) -> str:
483        return f"VTable({self.grid[0]}x{self.grid[1]})"
class Table:
 15class Table:
 16    def __init__(
 17        self, page, bbox: Rectangle, xlines: list, ylines: list, cbbox: Rectangle = None, is_register: bool = False
 18    ):
 19        self._page = page
 20        self._spacing = page._spacing
 21        self.bbox = bbox
 22        self.cbbox = None if is_register else cbbox
 23        self._type = "table"
 24        self._bit_headers = None
 25
 26        if not is_register:
 27            # Overlines of negated values are horizontal lines inside a cell that end on the glyphs below them.
 28            # A cell border ends at a vertical line, or on nothing when the table is missing a border.
 29            def _touches(x, y):
 30                if abs(x - bbox.left) < 1 or abs(x - bbox.right) < 1:
 31                    return True
 32                return any(abs(x - v.p0.x) < 1 and v.p0.y - 1 < y < v.p1.y + 1 for v in xlines)
 33
 34            def _is_overline(line):
 35                if _touches(line.p0.x, line.p0.y) or _touches(line.p1.x, line.p0.y):
 36                    return False
 37                return any(
 38                    # an overline drawn in pieces is joined, its pieces lie inside it
 39                    o.left - 1 < line.p0.x and line.p1.x < o.right + 1 and o.bottom - 1 < line.p0.y < o.top + 1
 40                    for o in page._overlines
 41                )
 42
 43            ylines = [line for line in ylines if not _is_overline(line)]
 44
 45        # Coalesce the vertical lines to detect the grid
 46        def _cluster(lines, key):
 47            atol = min(self._spacing["y_em"], self._spacing["x_em"]) / 4
 48            grid = defaultdict(list)
 49            last = -1e9
 50            current = -1e9
 51            for line in sorted(lines, key=key):
 52                if (last + atol) < key(line):
 53                    current = key(line)
 54                grid[current].append(line)
 55                last = key(line)
 56            return grid
 57
 58        xgrid = _cluster(xlines, lambda line: line.p0.x)
 59        ygrid = _cluster(ylines, lambda line: line.p0.y)
 60
 61        if is_register:
 62            self._type = "register"
 63
 64            # Find the positions of the top numbers
 65            clusters = []
 66            if lines := self._page.charlines_in_area(cbbox):
 67                if len(cluster := lines[0].clusters(self._page._spacing["x_em"] / 2)):
 68                    clusters.append((cluster, cbbox))
 69                else:
 70                    self.grid = (0, 0)
 71                    _LOGGER.error(f"Cannot find any bit position clusters! {self} ({self._page})")
 72
 73            # Find the positions of the second row of numbers
 74            if len(ygrid) > 2:
 75                for yi, (ypos0, ypos1) in enumerate(zip(sorted(ygrid), sorted(ygrid)[1:])):
 76                    nbbox = Rectangle(self.bbox.left, ygrid[ypos0][0].p0.y, self.bbox.right, ygrid[ypos1][0].p0.y)
 77                    if lines := self._page.charlines_in_area(nbbox):
 78                        if all(c.char.isnumeric() or c.unicode in {0x20, 0xA, 0xD} for c in lines[0].chars):
 79                            if not len(cluster := lines[0].clusters(self._page._spacing["x_em"] / 2)) % 16:
 80                                clusters.append((cluster, nbbox))
 81                                self._bit_headers = len(ygrid) - yi - 1
 82                            else:
 83                                self.grid = (len(cluster), 0)
 84                                _LOGGER.warning(
 85                                    f"Second bit pattern does not have 16 or 32 clusters! {self} ({self._page})"
 86                                )
 87                            break
 88
 89            # Merge these clusters to find their positions
 90            for cluster, bbox in clusters:
 91                # Close left and right side
 92                xgrid[sorted(xgrid)[0]].append(VLine(self.bbox.left, bbox.bottom, bbox.top))
 93                xgrid[sorted(xgrid)[-1]].append(VLine(self.bbox.right, bbox.bottom, bbox.top))
 94                # Now close the lines in between
 95                for cleft, cright in zip(cluster, cluster[1:]):
 96                    # find a line between the clusters
 97                    xpos = next(
 98                        (
 99                            (x, xgrid[x][0].p0.x)
100                            for x in sorted(xgrid)
101                            if cleft.bbox.right < xgrid[x][0].p0.x < cright.bbox.left
102                        ),
103                        None,
104                    )
105                    # Didn't find one, we must add one manually
106                    if xpos is None:
107                        xpos = (cleft.bbox.right + cright.bbox.left) / 2
108                        xpos = (int(round(xpos)), xpos)
109                    # Add it to the grid
110                    xgrid[xpos[0]].append(VLine(xpos[1], bbox.bottom, bbox.top))
111            # close the top
112            ygrid[self.bbox.top].append(HLine(self.bbox.top, self.bbox.left, self.bbox.right))
113
114        # Fix the position keys properly
115        self._xgrid = {int(round(statistics.fmean(m.p0.x for m in line))): line for line in xgrid.values()}
116        self._ygrid = {int(round(statistics.fmean(m.p0.y for m in line))): line for line in ygrid.values()}
117        # Map the positions to integers
118        self._xpos = list(sorted(self._xgrid))
119        self._ypos = list(sorted(self._ygrid))
120
121        self.grid = (len(self._xpos) - 1, len(self._ypos) - 1)
122        self._cells = None
123
124    def _cell_borders(self, x: int, y: int, bbox: Rectangle, mask: int = 0b1111) -> tuple[int, int, int, int]:
125        # left, bottom, right, top
126        borders = [0, 0, 0, 0]
127        mp = bbox.midpoint
128        if mask & 0b1000:  # Left
129            for line in self._xgrid[self._xpos[x]]:
130                if line.p0.y < mp.y < line.p1.y:
131                    borders[0] = line.width
132                    assert line.width
133                    break
134        if mask & 0b0010:  # Right
135            for line in self._xgrid[self._xpos[x + 1]]:
136                if line.p0.y < mp.y < line.p1.y:
137                    borders[2] = line.width
138                    assert line.width
139                    break
140        if mask & 0b0100:  # Bottom
141            for line in self._ygrid[self._ypos[y]]:
142                if line.p0.x < mp.x < line.p1.x:
143                    borders[1] = line.width
144                    assert line.width
145                    break
146        if mask & 0b0001:  # Top
147            for line in self._ygrid[self._ypos[y + 1]]:
148                if line.p0.x < mp.x < line.p1.x:
149                    borders[3] = line.width
150                    assert line.width
151                    break
152
153        return Borders(*borders)
154
155    def _fix_borders(self, cells, x: int, y: int):
156        # We are looking at the 9 neighbors around the cells
157        c = cells[(x, y)].borders
158        r = cells[(x + 1, y)].borders if cells[(x + 1, y)] is not None else Borders(0, 0, 1, 0)
159        t = cells[(x, y + 1)].borders if cells[(x, y + 1)] is not None else Borders(0, 1, 0, 0)
160
161        # if (not c.top and c.left and c.right and c.bottom) and "Reset value" in cell.content:
162        #     c.top = 1
163
164        # Open at the top into a span
165        if (not c.top and c.right) and (not t.right or not t.left):
166            c.top = 1
167            t.bottom = 1
168        # Open at the top and self is a span
169        if (not c.top and not c.right) and (t.right and t.left):
170            c.top = 1
171            t.bottom = 1
172
173        # Open to the right into a span
174        if (not c.right and c.top) and (not r.top or not r.bottom):
175            c.right = 1
176            r.left = 1
177        # Open to the right and self is a span
178        if (not c.right and not c.top) and (r.top and r.bottom):
179            c.right = 1
180            r.left = 1
181
182    @property
183    def cells(self) -> list[Cell]:
184        if self._cells is None:
185            if self.grid < (1, 1):
186                self._cells = []
187                return self._cells
188
189            # First determine the spans of cells by checking the borders
190            cells = defaultdict(lambda: None)
191            for yi, (y0, y1) in enumerate(zip(self._ypos, self._ypos[1:])):
192                for xi, (x0, x1) in enumerate(zip(self._xpos, self._xpos[1:])):
193                    bbox = Rectangle(x0, y0, x1, y1)
194                    borders = self._cell_borders(xi, yi, bbox, 0b1111)
195                    cells[(xi, yi)] = Cell(self, (self.grid[1] - 1 - yi, xi), bbox, borders, self._type == "register")
196
197            # Fix table cell borders via consistency checks
198            for yi in range(self.grid[1]):
199                for xi in range(self.grid[0]):
200                    self._fix_borders(cells, xi, yi)
201
202            # Merge the cells recursively
203            def _merge(px, py, x, y):
204                if cells[(x, y)] is None:
205                    return
206                # print(cells[(x, y)])
207                # Right border is open
208                if not cells[(x, y)].borders.right:
209                    if cells[(x + 1, y)] is not None:
210                        cells[(px, py)]._merge(cells[(x + 1, y)])
211                        _merge(px, py, x + 1, y)
212                        cells[(x + 1, y)] = None
213                # Top border is open
214                if not cells[(x, y)].borders.top:
215                    if cells[(x, y + 1)] is not None:
216                        cells[(px, py)]._merge(cells[(x, y + 1)])
217                        _merge(px, py, x, y + 1)
218                        cells[(x, y + 1)] = None
219
220            # Start merging in bottom left cell
221            for yi in range(self.grid[1]):
222                for xi in range(self.grid[0]):
223                    _merge(xi, yi, xi, yi)
224
225            # Find the header line, it is thicker than normal
226            y_header_pos = self.grid[1]
227            if self._type != "register":
228                if self.grid[1] > 1:
229                    line_widths = {
230                        round(line.width, 1) for llist in self._ygrid.values() for line in llist if line.width != 0.1
231                    }  # magic width of virtual borders
232                    if line_widths:
233                        line_width_max = max(line_widths) * 0.9
234                        if min(line_widths) < line_width_max:
235                            # Find the first thick line starting from the top
236                            y_header_pos = next(
237                                (
238                                    yi
239                                    for yi, ypos in reversed(list(enumerate(self._ypos)))
240                                    if any(line.width > line_width_max for line in self._ygrid[ypos])
241                                ),
242                                y_header_pos,
243                            )
244
245                # Map all the header
246                is_bold = []
247                for yi in range(0 if y_header_pos == self.grid[1] else y_header_pos, self.grid[1]):
248                    bbox = None
249                    for xi in range(self.grid[0]):
250                        if (cell := cells[(xi, yi)]) is not None:
251                            if bbox is None:
252                                bbox = cell.bbox
253                            else:
254                                bbox = bbox.joined(cell.bbox)
255                    if bbox is None:
256                        continue
257                    chars = self._page.chars_in_area(bbox)
258                    is_bold_pct = sum(1 if "Bold" in c.font else 0 for c in chars) / len(chars) if chars else 1
259                    is_bold.append((yi, is_bold_pct > self._spacing["th"]))
260
261                # Some tables have no bold cells at all
262                if all(not b[1] for b in is_bold):
263                    # Special case for two row tables without bold headers, but a bold line inbetween
264                    if self.grid[1] == 2 and y_header_pos == 1:
265                        y_header_pos = 2
266                else:
267                    if y_header_pos < self.grid[1]:
268                        # Find the lowest bold row starting from bold line
269                        y_header_pos = next((b[0] for b in is_bold if y_header_pos <= b[0] and b[1]), y_header_pos)
270                    else:
271                        # Find the lowest bold row starting from the top
272                        for b in reversed(is_bold):
273                            if not b[1]:
274                                break
275                            y_header_pos = b[0]
276
277            # Tell the header cells
278            for yi in range(y_header_pos, self.grid[1]):
279                for xi in range(self.grid[0]):
280                    if (cell := cells[(xi, yi)]) is not None:
281                        cell.is_header = True
282
283            # Flatten into array
284            cells = [c for c in cells.values() if c is not None]
285
286            # Normalize cells for registers by moving the lower ones right and up
287            if self._type == "register" and self._bit_headers is not None:
288                for cell in cells:
289                    if cell.y >= self._bit_headers:
290                        cell._move(16, -self._bit_headers)
291                    elif self._bit_headers <= 2 and cell.y == self._bit_headers - 1:
292                        cell._expand(0, 3 - self._bit_headers)
293                self.grid = (32, 4)
294
295            self._cells = list(sorted(cells, key=lambda c: c.positions[0]))
296
297        return self._cells
298
299    def append_bottom(self, other, merge_headers=True) -> bool:
300        debug = False
301        xgrid = self.grid[0]
302        if merge_headers and xgrid != other.grid[0]:
303            # Some tables have different column layouts due to span cells
304            # So we must correct the X positions of all cells accordingly
305            self_xheaders = defaultdict(set)
306            other_xheaders = defaultdict(set)
307            self_headers = [c for c in self.cells if c.is_header]
308            other_headers = [c for c in other.cells if c.is_header]
309            # Find the smallest set of spanning xpositions based on the header cells
310            for xpos in range(self.grid[0]):
311                for hcell in self_headers:
312                    if any(p[1] == xpos for p in hcell.positions):
313                        self_xheaders[hcell.x].add(xpos)
314            for xpos in range(other.grid[0]):
315                for hcell in other_headers:
316                    if any(p[1] == xpos for p in hcell.positions):
317                        other_xheaders[hcell.x].add(xpos)
318
319            # Compute the shared
320            self_heads = sorted(self_xheaders.keys())
321            other_heads = sorted(other_xheaders.keys())
322            xgrid = 0
323            merged_xheaders = defaultdict(set)
324            # Zip the groups together, these represent the matching header group spans
325            for self_xhead, other_xhead in zip(self_heads, other_heads):
326                size = max(len(self_xheaders[self_xhead]), len(other_xheaders[other_xhead]))
327                merged_xheaders[max(self_xhead, other_xhead)] = set(range(xgrid, xgrid + size))
328                xgrid += size
329
330            if debug:
331                print(len(self_xheaders), self_xheaders)
332                print(len(other_xheaders), other_xheaders)
333                print(len(merged_xheaders), merged_xheaders)
334            # If they are not equal length the table layouts are not compatible at all!
335            if len(self_heads) != len(other_heads):
336                _LOGGER.error(f"Failure to append table {other} ({other._page}) onto table {self} ({self._page})")
337                return False
338
339            # We want to stuff/move the cell positions inplace, therefore we start
340            # backwards moving the high numbers even higher, so that we don't
341            # overwrite ourselves and get stuck in an infinite loop
342            # Zip the groups together, these represent the matching header group spans
343            for self_xhead, other_xhead in zip(reversed(self_heads), reversed(other_heads)):
344                merged_xhead = max(self_xhead, other_xhead)
345                self_xpos = sorted(self_xheaders[self_xhead], reverse=True)
346                other_xpos = sorted(other_xheaders[other_xhead], reverse=True)
347                merged_xpos = sorted(merged_xheaders[merged_xhead], reverse=True)
348
349                def _insert_cells(cell, src, dsts, insert_only):
350                    assert dsts
351                    new_positions = []
352                    any_change = False
353                    for cpos in reversed(cell.positions):
354                        if insert_only:
355                            # If our set is empty we must only insert positions
356                            if cpos[1] == src:
357                                for xpos in dsts:
358                                    if debug:
359                                        print(f"Insert {cpos}++{(cpos[0], xpos)}")
360                                    new_positions.append((cpos[0], xpos))
361                                    any_change = True
362                            new_positions.append(cpos)
363                        else:
364                            # We must move (=replace and add) the span positions
365                            if cpos[1] == src:
366                                if debug:
367                                    print(f"Move {cpos}->{(cpos[0], dsts[0])}")
368                                new_positions.append((cpos[0], dsts[0]))
369                                any_change = True
370                            else:
371                                new_positions.append(cpos)
372                    if debug and any_change:
373                        print(f"{cell}: {src}->{dsts} {'I' if insert_only else 'M'}")
374                        print("old=", cell.positions, "new=", sorted(new_positions))
375                        print()
376                    assert new_positions
377                    assert len(new_positions) == len(set(new_positions))
378                    cell.positions = sorted(new_positions)
379                    cell._invalidate()
380
381                def _move_cells(cells, own_xpos):
382                    if debug:
383                        print()
384                        print(f"====== Rewrite rows: {own_xpos}->{merged_xpos} ======")
385                        print()
386
387                    for ii in range(max(len(own_xpos), len(merged_xpos))):
388                        insert_only = ii >= len(own_xpos)
389                        if insert_only:
390                            src = merged_xpos[ii - 1]
391                            dsts = merged_xpos[ii:]
392                            if debug:
393                                print(f"{src}->{dsts} I")
394                            for cell in cells:
395                                _insert_cells(cell, src, dsts, True)
396                            break
397                        else:
398                            src = own_xpos[ii]
399                            dsts = merged_xpos[ii : ii + 1]
400                            if debug:
401                                print(f"{src}->{dsts} M")
402                            for cell in cells:
403                                _insert_cells(cell, src, dsts, False)
404
405                if debug:
406                    print()
407                if self_xpos != merged_xpos:
408                    if debug:
409                        print(f"====== Self:  x={self_xhead}->{merged_xhead} xpos={self_xpos}->{merged_xpos}")
410                    _move_cells(self.cells, self_xpos)
411                if other_xpos != merged_xpos:
412                    if debug:
413                        print(
414                            f"====== Other: x={other_xhead}->{merged_xhead} xpos={other_xheaders[other_xhead]}->{merged_xheaders[merged_xhead]}"
415                        )
416                    _move_cells(other.cells, other_xpos)
417            if debug:
418                print()
419                print()
420                print()
421
422        # We must move the cells downwards now, but minus the header rows
423        rows = self.grid[1] - other.header_rows
424        for cell in other.cells:
425            # Discard the header cells, we just assume they are the same
426            if not cell.is_header:
427                cell._move(0, rows)
428                self.cells.append(cell)
429        self.cells.sort(key=lambda c: c.positions[0])
430        self.grid = (xgrid, other.grid[1] + rows)
431        if debug:
432            print(f"{self._page} -> {self.grid}")
433        return True
434
435    def append_side(self, other, expand=False) -> bool:
436        if self.grid[1] != other.grid[1]:
437            if expand:
438                _LOGGER.debug(
439                    f"Expanding bottom cells to match height: {self} ({self._page}) + {other} ({other._page})"
440                )
441                ymin = min(self.grid[1], other.grid[1])
442                ymax = max(self.grid[1], other.grid[1])
443                etable = other if self.grid[1] > other.grid[1] else self
444                for cell in etable.cells:
445                    if any(p[0] == ymin - 1 for p in cell.positions):
446                        cell._expand(0, ymax - ymin)
447                etable.grid = (etable.grid[0], ymax)
448            else:
449                _LOGGER.error(f"Unable to append table at side: {self} ({self._page}) + {other} ({other._page})")
450                return False
451
452        # We must move all cells to the right now
453        columns = self.grid[0]
454        for cell in other.cells:
455            cell._move(columns, 0)
456            self.cells.append(cell)
457        self.cells.sort(key=lambda c: c.positions[0])
458        self.grid = (other.grid[0] + columns, max(self.grid[1], other.grid[1]))
459        return True
460
461    @cached_property
462    def header_rows(self) -> int:
463        header_cells = [c for c in self.cells if c.is_header]
464        if header_cells:
465            return max(c.positions[-1][0] + 1 for c in header_cells)
466        return 0
467
468    def __repr__(self) -> str:
469        return f"Table({self.grid[0]}x{self.grid[1]})"
Table( page, bbox: modm_data.utils.Rectangle, xlines: list, ylines: list, cbbox: modm_data.utils.Rectangle = None, is_register: bool = False)
 16    def __init__(
 17        self, page, bbox: Rectangle, xlines: list, ylines: list, cbbox: Rectangle = None, is_register: bool = False
 18    ):
 19        self._page = page
 20        self._spacing = page._spacing
 21        self.bbox = bbox
 22        self.cbbox = None if is_register else cbbox
 23        self._type = "table"
 24        self._bit_headers = None
 25
 26        if not is_register:
 27            # Overlines of negated values are horizontal lines inside a cell that end on the glyphs below them.
 28            # A cell border ends at a vertical line, or on nothing when the table is missing a border.
 29            def _touches(x, y):
 30                if abs(x - bbox.left) < 1 or abs(x - bbox.right) < 1:
 31                    return True
 32                return any(abs(x - v.p0.x) < 1 and v.p0.y - 1 < y < v.p1.y + 1 for v in xlines)
 33
 34            def _is_overline(line):
 35                if _touches(line.p0.x, line.p0.y) or _touches(line.p1.x, line.p0.y):
 36                    return False
 37                return any(
 38                    # an overline drawn in pieces is joined, its pieces lie inside it
 39                    o.left - 1 < line.p0.x and line.p1.x < o.right + 1 and o.bottom - 1 < line.p0.y < o.top + 1
 40                    for o in page._overlines
 41                )
 42
 43            ylines = [line for line in ylines if not _is_overline(line)]
 44
 45        # Coalesce the vertical lines to detect the grid
 46        def _cluster(lines, key):
 47            atol = min(self._spacing["y_em"], self._spacing["x_em"]) / 4
 48            grid = defaultdict(list)
 49            last = -1e9
 50            current = -1e9
 51            for line in sorted(lines, key=key):
 52                if (last + atol) < key(line):
 53                    current = key(line)
 54                grid[current].append(line)
 55                last = key(line)
 56            return grid
 57
 58        xgrid = _cluster(xlines, lambda line: line.p0.x)
 59        ygrid = _cluster(ylines, lambda line: line.p0.y)
 60
 61        if is_register:
 62            self._type = "register"
 63
 64            # Find the positions of the top numbers
 65            clusters = []
 66            if lines := self._page.charlines_in_area(cbbox):
 67                if len(cluster := lines[0].clusters(self._page._spacing["x_em"] / 2)):
 68                    clusters.append((cluster, cbbox))
 69                else:
 70                    self.grid = (0, 0)
 71                    _LOGGER.error(f"Cannot find any bit position clusters! {self} ({self._page})")
 72
 73            # Find the positions of the second row of numbers
 74            if len(ygrid) > 2:
 75                for yi, (ypos0, ypos1) in enumerate(zip(sorted(ygrid), sorted(ygrid)[1:])):
 76                    nbbox = Rectangle(self.bbox.left, ygrid[ypos0][0].p0.y, self.bbox.right, ygrid[ypos1][0].p0.y)
 77                    if lines := self._page.charlines_in_area(nbbox):
 78                        if all(c.char.isnumeric() or c.unicode in {0x20, 0xA, 0xD} for c in lines[0].chars):
 79                            if not len(cluster := lines[0].clusters(self._page._spacing["x_em"] / 2)) % 16:
 80                                clusters.append((cluster, nbbox))
 81                                self._bit_headers = len(ygrid) - yi - 1
 82                            else:
 83                                self.grid = (len(cluster), 0)
 84                                _LOGGER.warning(
 85                                    f"Second bit pattern does not have 16 or 32 clusters! {self} ({self._page})"
 86                                )
 87                            break
 88
 89            # Merge these clusters to find their positions
 90            for cluster, bbox in clusters:
 91                # Close left and right side
 92                xgrid[sorted(xgrid)[0]].append(VLine(self.bbox.left, bbox.bottom, bbox.top))
 93                xgrid[sorted(xgrid)[-1]].append(VLine(self.bbox.right, bbox.bottom, bbox.top))
 94                # Now close the lines in between
 95                for cleft, cright in zip(cluster, cluster[1:]):
 96                    # find a line between the clusters
 97                    xpos = next(
 98                        (
 99                            (x, xgrid[x][0].p0.x)
100                            for x in sorted(xgrid)
101                            if cleft.bbox.right < xgrid[x][0].p0.x < cright.bbox.left
102                        ),
103                        None,
104                    )
105                    # Didn't find one, we must add one manually
106                    if xpos is None:
107                        xpos = (cleft.bbox.right + cright.bbox.left) / 2
108                        xpos = (int(round(xpos)), xpos)
109                    # Add it to the grid
110                    xgrid[xpos[0]].append(VLine(xpos[1], bbox.bottom, bbox.top))
111            # close the top
112            ygrid[self.bbox.top].append(HLine(self.bbox.top, self.bbox.left, self.bbox.right))
113
114        # Fix the position keys properly
115        self._xgrid = {int(round(statistics.fmean(m.p0.x for m in line))): line for line in xgrid.values()}
116        self._ygrid = {int(round(statistics.fmean(m.p0.y for m in line))): line for line in ygrid.values()}
117        # Map the positions to integers
118        self._xpos = list(sorted(self._xgrid))
119        self._ypos = list(sorted(self._ygrid))
120
121        self.grid = (len(self._xpos) - 1, len(self._ypos) - 1)
122        self._cells = None
bbox
cbbox
grid
cells: list[modm_data.pdf2html.cell.Cell]
182    @property
183    def cells(self) -> list[Cell]:
184        if self._cells is None:
185            if self.grid < (1, 1):
186                self._cells = []
187                return self._cells
188
189            # First determine the spans of cells by checking the borders
190            cells = defaultdict(lambda: None)
191            for yi, (y0, y1) in enumerate(zip(self._ypos, self._ypos[1:])):
192                for xi, (x0, x1) in enumerate(zip(self._xpos, self._xpos[1:])):
193                    bbox = Rectangle(x0, y0, x1, y1)
194                    borders = self._cell_borders(xi, yi, bbox, 0b1111)
195                    cells[(xi, yi)] = Cell(self, (self.grid[1] - 1 - yi, xi), bbox, borders, self._type == "register")
196
197            # Fix table cell borders via consistency checks
198            for yi in range(self.grid[1]):
199                for xi in range(self.grid[0]):
200                    self._fix_borders(cells, xi, yi)
201
202            # Merge the cells recursively
203            def _merge(px, py, x, y):
204                if cells[(x, y)] is None:
205                    return
206                # print(cells[(x, y)])
207                # Right border is open
208                if not cells[(x, y)].borders.right:
209                    if cells[(x + 1, y)] is not None:
210                        cells[(px, py)]._merge(cells[(x + 1, y)])
211                        _merge(px, py, x + 1, y)
212                        cells[(x + 1, y)] = None
213                # Top border is open
214                if not cells[(x, y)].borders.top:
215                    if cells[(x, y + 1)] is not None:
216                        cells[(px, py)]._merge(cells[(x, y + 1)])
217                        _merge(px, py, x, y + 1)
218                        cells[(x, y + 1)] = None
219
220            # Start merging in bottom left cell
221            for yi in range(self.grid[1]):
222                for xi in range(self.grid[0]):
223                    _merge(xi, yi, xi, yi)
224
225            # Find the header line, it is thicker than normal
226            y_header_pos = self.grid[1]
227            if self._type != "register":
228                if self.grid[1] > 1:
229                    line_widths = {
230                        round(line.width, 1) for llist in self._ygrid.values() for line in llist if line.width != 0.1
231                    }  # magic width of virtual borders
232                    if line_widths:
233                        line_width_max = max(line_widths) * 0.9
234                        if min(line_widths) < line_width_max:
235                            # Find the first thick line starting from the top
236                            y_header_pos = next(
237                                (
238                                    yi
239                                    for yi, ypos in reversed(list(enumerate(self._ypos)))
240                                    if any(line.width > line_width_max for line in self._ygrid[ypos])
241                                ),
242                                y_header_pos,
243                            )
244
245                # Map all the header
246                is_bold = []
247                for yi in range(0 if y_header_pos == self.grid[1] else y_header_pos, self.grid[1]):
248                    bbox = None
249                    for xi in range(self.grid[0]):
250                        if (cell := cells[(xi, yi)]) is not None:
251                            if bbox is None:
252                                bbox = cell.bbox
253                            else:
254                                bbox = bbox.joined(cell.bbox)
255                    if bbox is None:
256                        continue
257                    chars = self._page.chars_in_area(bbox)
258                    is_bold_pct = sum(1 if "Bold" in c.font else 0 for c in chars) / len(chars) if chars else 1
259                    is_bold.append((yi, is_bold_pct > self._spacing["th"]))
260
261                # Some tables have no bold cells at all
262                if all(not b[1] for b in is_bold):
263                    # Special case for two row tables without bold headers, but a bold line inbetween
264                    if self.grid[1] == 2 and y_header_pos == 1:
265                        y_header_pos = 2
266                else:
267                    if y_header_pos < self.grid[1]:
268                        # Find the lowest bold row starting from bold line
269                        y_header_pos = next((b[0] for b in is_bold if y_header_pos <= b[0] and b[1]), y_header_pos)
270                    else:
271                        # Find the lowest bold row starting from the top
272                        for b in reversed(is_bold):
273                            if not b[1]:
274                                break
275                            y_header_pos = b[0]
276
277            # Tell the header cells
278            for yi in range(y_header_pos, self.grid[1]):
279                for xi in range(self.grid[0]):
280                    if (cell := cells[(xi, yi)]) is not None:
281                        cell.is_header = True
282
283            # Flatten into array
284            cells = [c for c in cells.values() if c is not None]
285
286            # Normalize cells for registers by moving the lower ones right and up
287            if self._type == "register" and self._bit_headers is not None:
288                for cell in cells:
289                    if cell.y >= self._bit_headers:
290                        cell._move(16, -self._bit_headers)
291                    elif self._bit_headers <= 2 and cell.y == self._bit_headers - 1:
292                        cell._expand(0, 3 - self._bit_headers)
293                self.grid = (32, 4)
294
295            self._cells = list(sorted(cells, key=lambda c: c.positions[0]))
296
297        return self._cells
def append_bottom(self, other, merge_headers=True) -> bool:
299    def append_bottom(self, other, merge_headers=True) -> bool:
300        debug = False
301        xgrid = self.grid[0]
302        if merge_headers and xgrid != other.grid[0]:
303            # Some tables have different column layouts due to span cells
304            # So we must correct the X positions of all cells accordingly
305            self_xheaders = defaultdict(set)
306            other_xheaders = defaultdict(set)
307            self_headers = [c for c in self.cells if c.is_header]
308            other_headers = [c for c in other.cells if c.is_header]
309            # Find the smallest set of spanning xpositions based on the header cells
310            for xpos in range(self.grid[0]):
311                for hcell in self_headers:
312                    if any(p[1] == xpos for p in hcell.positions):
313                        self_xheaders[hcell.x].add(xpos)
314            for xpos in range(other.grid[0]):
315                for hcell in other_headers:
316                    if any(p[1] == xpos for p in hcell.positions):
317                        other_xheaders[hcell.x].add(xpos)
318
319            # Compute the shared
320            self_heads = sorted(self_xheaders.keys())
321            other_heads = sorted(other_xheaders.keys())
322            xgrid = 0
323            merged_xheaders = defaultdict(set)
324            # Zip the groups together, these represent the matching header group spans
325            for self_xhead, other_xhead in zip(self_heads, other_heads):
326                size = max(len(self_xheaders[self_xhead]), len(other_xheaders[other_xhead]))
327                merged_xheaders[max(self_xhead, other_xhead)] = set(range(xgrid, xgrid + size))
328                xgrid += size
329
330            if debug:
331                print(len(self_xheaders), self_xheaders)
332                print(len(other_xheaders), other_xheaders)
333                print(len(merged_xheaders), merged_xheaders)
334            # If they are not equal length the table layouts are not compatible at all!
335            if len(self_heads) != len(other_heads):
336                _LOGGER.error(f"Failure to append table {other} ({other._page}) onto table {self} ({self._page})")
337                return False
338
339            # We want to stuff/move the cell positions inplace, therefore we start
340            # backwards moving the high numbers even higher, so that we don't
341            # overwrite ourselves and get stuck in an infinite loop
342            # Zip the groups together, these represent the matching header group spans
343            for self_xhead, other_xhead in zip(reversed(self_heads), reversed(other_heads)):
344                merged_xhead = max(self_xhead, other_xhead)
345                self_xpos = sorted(self_xheaders[self_xhead], reverse=True)
346                other_xpos = sorted(other_xheaders[other_xhead], reverse=True)
347                merged_xpos = sorted(merged_xheaders[merged_xhead], reverse=True)
348
349                def _insert_cells(cell, src, dsts, insert_only):
350                    assert dsts
351                    new_positions = []
352                    any_change = False
353                    for cpos in reversed(cell.positions):
354                        if insert_only:
355                            # If our set is empty we must only insert positions
356                            if cpos[1] == src:
357                                for xpos in dsts:
358                                    if debug:
359                                        print(f"Insert {cpos}++{(cpos[0], xpos)}")
360                                    new_positions.append((cpos[0], xpos))
361                                    any_change = True
362                            new_positions.append(cpos)
363                        else:
364                            # We must move (=replace and add) the span positions
365                            if cpos[1] == src:
366                                if debug:
367                                    print(f"Move {cpos}->{(cpos[0], dsts[0])}")
368                                new_positions.append((cpos[0], dsts[0]))
369                                any_change = True
370                            else:
371                                new_positions.append(cpos)
372                    if debug and any_change:
373                        print(f"{cell}: {src}->{dsts} {'I' if insert_only else 'M'}")
374                        print("old=", cell.positions, "new=", sorted(new_positions))
375                        print()
376                    assert new_positions
377                    assert len(new_positions) == len(set(new_positions))
378                    cell.positions = sorted(new_positions)
379                    cell._invalidate()
380
381                def _move_cells(cells, own_xpos):
382                    if debug:
383                        print()
384                        print(f"====== Rewrite rows: {own_xpos}->{merged_xpos} ======")
385                        print()
386
387                    for ii in range(max(len(own_xpos), len(merged_xpos))):
388                        insert_only = ii >= len(own_xpos)
389                        if insert_only:
390                            src = merged_xpos[ii - 1]
391                            dsts = merged_xpos[ii:]
392                            if debug:
393                                print(f"{src}->{dsts} I")
394                            for cell in cells:
395                                _insert_cells(cell, src, dsts, True)
396                            break
397                        else:
398                            src = own_xpos[ii]
399                            dsts = merged_xpos[ii : ii + 1]
400                            if debug:
401                                print(f"{src}->{dsts} M")
402                            for cell in cells:
403                                _insert_cells(cell, src, dsts, False)
404
405                if debug:
406                    print()
407                if self_xpos != merged_xpos:
408                    if debug:
409                        print(f"====== Self:  x={self_xhead}->{merged_xhead} xpos={self_xpos}->{merged_xpos}")
410                    _move_cells(self.cells, self_xpos)
411                if other_xpos != merged_xpos:
412                    if debug:
413                        print(
414                            f"====== Other: x={other_xhead}->{merged_xhead} xpos={other_xheaders[other_xhead]}->{merged_xheaders[merged_xhead]}"
415                        )
416                    _move_cells(other.cells, other_xpos)
417            if debug:
418                print()
419                print()
420                print()
421
422        # We must move the cells downwards now, but minus the header rows
423        rows = self.grid[1] - other.header_rows
424        for cell in other.cells:
425            # Discard the header cells, we just assume they are the same
426            if not cell.is_header:
427                cell._move(0, rows)
428                self.cells.append(cell)
429        self.cells.sort(key=lambda c: c.positions[0])
430        self.grid = (xgrid, other.grid[1] + rows)
431        if debug:
432            print(f"{self._page} -> {self.grid}")
433        return True
def append_side(self, other, expand=False) -> bool:
435    def append_side(self, other, expand=False) -> bool:
436        if self.grid[1] != other.grid[1]:
437            if expand:
438                _LOGGER.debug(
439                    f"Expanding bottom cells to match height: {self} ({self._page}) + {other} ({other._page})"
440                )
441                ymin = min(self.grid[1], other.grid[1])
442                ymax = max(self.grid[1], other.grid[1])
443                etable = other if self.grid[1] > other.grid[1] else self
444                for cell in etable.cells:
445                    if any(p[0] == ymin - 1 for p in cell.positions):
446                        cell._expand(0, ymax - ymin)
447                etable.grid = (etable.grid[0], ymax)
448            else:
449                _LOGGER.error(f"Unable to append table at side: {self} ({self._page}) + {other} ({other._page})")
450                return False
451
452        # We must move all cells to the right now
453        columns = self.grid[0]
454        for cell in other.cells:
455            cell._move(columns, 0)
456            self.cells.append(cell)
457        self.cells.sort(key=lambda c: c.positions[0])
458        self.grid = (other.grid[0] + columns, max(self.grid[1], other.grid[1]))
459        return True
header_rows: int
461    @cached_property
462    def header_rows(self) -> int:
463        header_cells = [c for c in self.cells if c.is_header]
464        if header_cells:
465            return max(c.positions[-1][0] + 1 for c in header_cells)
466        return 0
class VirtualTable(Table):
472class VirtualTable(Table):
473    def __init__(self, page, bbox, cells, table_type=None):
474        self._page = page
475        self._spacing = page._spacing
476        self._type = table_type or "virtual"
477        self.bbox = bbox
478        self._cells = cells
479        self.grid = (max(c.x for c in cells) + 1, max(c.y for c in cells) + 1)
480        for cell in cells:
481            cell._table = self
482
483    def __repr__(self) -> str:
484        return f"VTable({self.grid[0]}x{self.grid[1]})"
VirtualTable(page, bbox, cells, table_type=None)
473    def __init__(self, page, bbox, cells, table_type=None):
474        self._page = page
475        self._spacing = page._spacing
476        self._type = table_type or "virtual"
477        self.bbox = bbox
478        self._cells = cells
479        self.grid = (max(c.x for c in cells) + 1, max(c.y for c in cells) + 1)
480        for cell in cells:
481            cell._table = self
bbox
grid