modm_data.pdf2html.stmicro
57class Document(PdfDocument): 58 def __init__(self, path: str): 59 super().__init__(path) 60 self._path = path 61 self._normalize = _normalize_document 62 self._anchors = {} 63 # The ids of the headings, tables and figures on each page 64 self._named = {} 65 # Chapter conversions write placeholders for their links and collect the ids of their own pages instead 66 self._deferred = False 67 self._collected = {} 68 69 @cached_property 70 def chapters(self) -> list[tuple[int, int, str]]: 71 """The page ranges [start, stop) and HTML file names of the chapters of the HTML archive.""" 72 dests = [(0, "introduction")] 73 for toc in self.toc: 74 if toc.level == 0 and not toc.title.startswith("Table"): 75 title = toc.title.lower().strip("0123456789").strip() 76 title = re.sub(r"[\(\)/®&\n\r,;:™'’\"]", "", title) 77 title = re.sub(r"[ -]", "_", title) 78 title = re.sub(r"_+", "_", title) 79 title = title.replace("²", "2") 80 if not any(c in toc.title for c in {"Contents", "List of ", "Index"}): 81 dests.append((toc.page_index, title)) 82 dests.append((self.page_count, None)) 83 ranges = [(p0, p1, t0) for (p0, t0), (p1, t1) in zip(dests, dests[1:]) if p0 != p1] 84 return [(p0, p1, f"chapter_{ii}_{title}.html") for ii, (p0, p1, title) in enumerate(ranges)] 85 86 @cached_property 87 def destinations(self) -> dict[int, set[tuple[float | None, float | None]]]: 88 """The positions of all link destinations in the document by page index.""" 89 destinations = defaultdict(set) 90 for index in range(self.page_count): 91 # Only the links are needed, which is much faster without the text of the page 92 page = pp.raw.FPDF_LoadPage(self, index) 93 pos, link = ctypes.c_int(0), pp.raw.FPDF_LINK() 94 while pp.raw.FPDFLink_Enumerate(page, pos, link): 95 page_index, *location = link_destination(self, link) 96 if page_index >= 0: 97 destinations[page_index].add(tuple(location)) 98 pp.raw.FPDF_ClosePage(page) 99 return destinations 100 101 def _page_anchors(self, index: int) -> tuple[dict[tuple, str], set[str]]: 102 """ 103 The ids of all link destinations on one page and of all its headings, 104 tables and figures. The page is loaded only once for them. 105 """ 106 page = self.page(index) 107 return {location: page.anchor_at(*location) for location in self.destinations.get(index, ())}, page.named_ids 108 109 def _add_page_anchors(self, index: int, anchors: dict, named: set): 110 self._anchors.update(((index, location), anchor) for location, anchor in anchors.items()) 111 self._named[index] = set(named) 112 113 def resolve_anchors(self, processes: int = None): 114 """Resolves the ids of all link destinations in parallel, each page is loaded only once.""" 115 # A caption may start on the page after the destination 116 pages = {i for index in self.destinations for i in (index, index + 1) if i < self.page_count} 117 indices = sorted(index for index in pages if index not in self._named) 118 with multiprocessing.Pool(processes, _init_worker, (self._path, self.destinations)) as pool: 119 for index, anchors, named in pool.imap_unordered(_resolve_page, indices, chunksize=4): 120 self._add_page_anchors(index, anchors, named) 121 122 def save_destinations(self, path: Path, resolve: bool = True): 123 """ 124 Saves the link destinations and their ids, so that the conversions of 125 the chapters neither search nor resolve them again. Without resolving, 126 the chapters resolve the destinations on their own pages, see 127 `resolve_deferred_links()`. 128 """ 129 if resolve: 130 self.resolve_anchors() 131 destinations = { 132 index: [[*location, self._anchors.get((index, location))] for location in sorted(dests, key=str)] 133 for index, dests in self.destinations.items() 134 } 135 named = {index: sorted(ids) for index, ids in self._named.items()} 136 Path(path).write_text(json.dumps({"destinations": destinations, "named": named, "deferred": not resolve})) 137 138 def load_destinations(self, path: Path): 139 """Loads the link destinations and their ids saved by `save_destinations()`.""" 140 data = json.loads(Path(path).read_text()) 141 self._deferred = data.get("deferred", False) 142 destinations = data["destinations"] 143 self._named.update((int(index), set(ids)) for index, ids in data["named"].items()) 144 self.destinations = {int(index): {(x, y) for x, y, _ in dests} for index, dests in destinations.items()} 145 self._anchors.update( 146 ((int(index), (x, y)), anchor) 147 for index, dests in destinations.items() 148 for x, y, anchor in dests 149 if anchor is not None 150 ) 151 152 def collect_page(self, page): 153 """Keeps the ids of a converted page for `resolve_deferred_links()`, its lines are built already.""" 154 if self._deferred: 155 anchors = [[*location, page.anchor_at(*location)] for location in self.destinations.get(page.index, ())] 156 self._collected[page.index] = {"anchors": anchors, "named": sorted(page.named_ids)} 157 158 def save_collected(self, path: Path): 159 if self._deferred: 160 Path(path).write_text(json.dumps(self._collected)) 161 162 def _named_ids(self, index: int) -> set[str]: 163 if index not in self._named: 164 self._add_page_anchors(index, *self._page_anchors(index)) 165 return self._named[index] 166 167 def link_target(self, link, text: str = "") -> str | None: 168 """ 169 The URL of an external link, or the chapter file of the HTML archive 170 and the id of the heading, table or figure at the link destination. 171 Destinations without such an id fall back to the id of their page. 172 """ 173 if link.page_index < 0: 174 return link.url 175 if self._deferred: 176 # Resolved once all chapters are converted, the text decides about a named target already 177 match = re.match(r"(Section|Table|Figure)\s+(\d+(?:\.\d+)*)\b", text) 178 named = f"{match.group(1).lower()}{match.group(2)}" if match else "" 179 return f"@{link.page_index}:{link.location[0]!r}:{link.location[1]!r}:{named}" 180 filename = next((f for p0, p1, f in self.chapters if p0 <= link.page_index < p1), "") 181 key = (link.page_index, link.location) 182 if key not in self._anchors: 183 # All destinations of the page at once, so that the page is loaded only once 184 self._add_page_anchors(link.page_index, *self._page_anchors(link.page_index)) 185 if (anchor := self._anchors.get(key)) is None: 186 anchor = self._anchors[key] = self.page(link.page_index).anchor_at(*link.location) 187 target = f"{filename}#{anchor}" 188 # The page or line of the destination always has an id, a heading, table or figure may be missing when 189 # pdf2html did not detect it, see `resolve_link_fallbacks()`. 190 fallback = target if anchor.startswith("page") else f"{filename}#page{link.page_index + 1}" 191 # A link named after a table, figure or section goes to it, if it is on the destination page or the next. 192 # The destination position alone often lands on the heading above a caption or between both. 193 if match := re.match(r"(Section|Table|Figure)\s+(\d+(?:\.\d+)*)\b", text): 194 named = f"{match.group(1).lower()}{match.group(2)}" 195 for index in (link.page_index, link.page_index + 1): 196 if index < self.page_count and named in self._named_ids(index): 197 named_file = next((f for p0, p1, f in self.chapters if p0 <= index < p1), "") 198 return f"{named_file}#{named} {fallback}" 199 if target == fallback: 200 return target 201 return f"{target} {fallback}" 202 203 def page(self, index: int) -> StmPage: 204 assert index < self.page_count 205 return StmPage(self, index) 206 207 def __repr__(self) -> str: 208 return f"STMicroDoc({self.name})"
The PDF document is the root of the entire data structure and provides access to PDF metadata, the table of contents, as well as individual pages.
You should extend from this class for a specific vendor to provide the
correct page class from page() function.
This class is a convenience wrapper with caching around the high-level APIs of pypdfium.
58 def __init__(self, path: str): 59 super().__init__(path) 60 self._path = path 61 self._normalize = _normalize_document 62 self._anchors = {} 63 # The ids of the headings, tables and figures on each page 64 self._named = {} 65 # Chapter conversions write placeholders for their links and collect the ids of their own pages instead 66 self._deferred = False 67 self._collected = {}
Parameters
- path: Path to the PDF to open.
69 @cached_property 70 def chapters(self) -> list[tuple[int, int, str]]: 71 """The page ranges [start, stop) and HTML file names of the chapters of the HTML archive.""" 72 dests = [(0, "introduction")] 73 for toc in self.toc: 74 if toc.level == 0 and not toc.title.startswith("Table"): 75 title = toc.title.lower().strip("0123456789").strip() 76 title = re.sub(r"[\(\)/®&\n\r,;:™'’\"]", "", title) 77 title = re.sub(r"[ -]", "_", title) 78 title = re.sub(r"_+", "_", title) 79 title = title.replace("²", "2") 80 if not any(c in toc.title for c in {"Contents", "List of ", "Index"}): 81 dests.append((toc.page_index, title)) 82 dests.append((self.page_count, None)) 83 ranges = [(p0, p1, t0) for (p0, t0), (p1, t1) in zip(dests, dests[1:]) if p0 != p1] 84 return [(p0, p1, f"chapter_{ii}_{title}.html") for ii, (p0, p1, title) in enumerate(ranges)]
The page ranges [start, stop) and HTML file names of the chapters of the HTML archive.
86 @cached_property 87 def destinations(self) -> dict[int, set[tuple[float | None, float | None]]]: 88 """The positions of all link destinations in the document by page index.""" 89 destinations = defaultdict(set) 90 for index in range(self.page_count): 91 # Only the links are needed, which is much faster without the text of the page 92 page = pp.raw.FPDF_LoadPage(self, index) 93 pos, link = ctypes.c_int(0), pp.raw.FPDF_LINK() 94 while pp.raw.FPDFLink_Enumerate(page, pos, link): 95 page_index, *location = link_destination(self, link) 96 if page_index >= 0: 97 destinations[page_index].add(tuple(location)) 98 pp.raw.FPDF_ClosePage(page) 99 return destinations
The positions of all link destinations in the document by page index.
113 def resolve_anchors(self, processes: int = None): 114 """Resolves the ids of all link destinations in parallel, each page is loaded only once.""" 115 # A caption may start on the page after the destination 116 pages = {i for index in self.destinations for i in (index, index + 1) if i < self.page_count} 117 indices = sorted(index for index in pages if index not in self._named) 118 with multiprocessing.Pool(processes, _init_worker, (self._path, self.destinations)) as pool: 119 for index, anchors, named in pool.imap_unordered(_resolve_page, indices, chunksize=4): 120 self._add_page_anchors(index, anchors, named)
Resolves the ids of all link destinations in parallel, each page is loaded only once.
122 def save_destinations(self, path: Path, resolve: bool = True): 123 """ 124 Saves the link destinations and their ids, so that the conversions of 125 the chapters neither search nor resolve them again. Without resolving, 126 the chapters resolve the destinations on their own pages, see 127 `resolve_deferred_links()`. 128 """ 129 if resolve: 130 self.resolve_anchors() 131 destinations = { 132 index: [[*location, self._anchors.get((index, location))] for location in sorted(dests, key=str)] 133 for index, dests in self.destinations.items() 134 } 135 named = {index: sorted(ids) for index, ids in self._named.items()} 136 Path(path).write_text(json.dumps({"destinations": destinations, "named": named, "deferred": not resolve}))
Saves the link destinations and their ids, so that the conversions of
the chapters neither search nor resolve them again. Without resolving,
the chapters resolve the destinations on their own pages, see
resolve_deferred_links().
138 def load_destinations(self, path: Path): 139 """Loads the link destinations and their ids saved by `save_destinations()`.""" 140 data = json.loads(Path(path).read_text()) 141 self._deferred = data.get("deferred", False) 142 destinations = data["destinations"] 143 self._named.update((int(index), set(ids)) for index, ids in data["named"].items()) 144 self.destinations = {int(index): {(x, y) for x, y, _ in dests} for index, dests in destinations.items()} 145 self._anchors.update( 146 ((int(index), (x, y)), anchor) 147 for index, dests in destinations.items() 148 for x, y, anchor in dests 149 if anchor is not None 150 )
Loads the link destinations and their ids saved by save_destinations().
152 def collect_page(self, page): 153 """Keeps the ids of a converted page for `resolve_deferred_links()`, its lines are built already.""" 154 if self._deferred: 155 anchors = [[*location, page.anchor_at(*location)] for location in self.destinations.get(page.index, ())] 156 self._collected[page.index] = {"anchors": anchors, "named": sorted(page.named_ids)}
Keeps the ids of a converted page for resolve_deferred_links(), its lines are built already.
167 def link_target(self, link, text: str = "") -> str | None: 168 """ 169 The URL of an external link, or the chapter file of the HTML archive 170 and the id of the heading, table or figure at the link destination. 171 Destinations without such an id fall back to the id of their page. 172 """ 173 if link.page_index < 0: 174 return link.url 175 if self._deferred: 176 # Resolved once all chapters are converted, the text decides about a named target already 177 match = re.match(r"(Section|Table|Figure)\s+(\d+(?:\.\d+)*)\b", text) 178 named = f"{match.group(1).lower()}{match.group(2)}" if match else "" 179 return f"@{link.page_index}:{link.location[0]!r}:{link.location[1]!r}:{named}" 180 filename = next((f for p0, p1, f in self.chapters if p0 <= link.page_index < p1), "") 181 key = (link.page_index, link.location) 182 if key not in self._anchors: 183 # All destinations of the page at once, so that the page is loaded only once 184 self._add_page_anchors(link.page_index, *self._page_anchors(link.page_index)) 185 if (anchor := self._anchors.get(key)) is None: 186 anchor = self._anchors[key] = self.page(link.page_index).anchor_at(*link.location) 187 target = f"{filename}#{anchor}" 188 # The page or line of the destination always has an id, a heading, table or figure may be missing when 189 # pdf2html did not detect it, see `resolve_link_fallbacks()`. 190 fallback = target if anchor.startswith("page") else f"{filename}#page{link.page_index + 1}" 191 # A link named after a table, figure or section goes to it, if it is on the destination page or the next. 192 # The destination position alone often lands on the heading above a caption or between both. 193 if match := re.match(r"(Section|Table|Figure)\s+(\d+(?:\.\d+)*)\b", text): 194 named = f"{match.group(1).lower()}{match.group(2)}" 195 for index in (link.page_index, link.page_index + 1): 196 if index < self.page_count and named in self._named_ids(index): 197 named_file = next((f for p0, p1, f in self.chapters if p0 <= index < p1), "") 198 return f"{named_file}#{named} {fallback}" 199 if target == fallback: 200 return target 201 return f"{target} {fallback}"
The URL of an external link, or the chapter file of the HTML archive and the id of the heading, table or figure at the link destination. Destinations without such an id fall back to the id of their page.
203 def page(self, index: int) -> StmPage: 204 assert index < self.page_count 205 return StmPage(self, index)
Parameters
- index: 0-indexed page number.
Returns
the page object for the index.
Inherited Members
- modm_data.pdf.document.Document
- name
- metadata
- toc
- identifier_permanent
- identifier_changing
- page_count
- pages
- pypdfium2._helpers.document.PdfDocument
- parent
- new
- formenv
- init_forms
- close_forms
- get_formtype
- get_pagemode
- is_tagged
- save
- get_identifier
- get_version
- get_metadata_value
- METADATA_KEYS
- get_metadata_dict
- count_attachments
- get_attachment
- new_attachment
- del_attachment
- get_page
- new_page
- del_page
- import_pages
- get_page_size
- get_page_label
- page_as_xobject
- get_toc
- pypdfium2.internal.bases.AutoCloseable
- close
298class Page(BasePage): 299 def __init__(self, document, index: int): 300 super().__init__(document, index) 301 producer = self.pdf.metadata.get("Producer", "").lower() 302 self._template = "black_white" 303 if "acrobat" in producer or "adobe" in producer: 304 pass 305 elif "antenna" in producer: 306 self._template = "blue_gray" 307 else: 308 _LOGGER.error(f"Unknown page template! Defaulting to Black/White template. '{producer}'") 309 310 if "blue_gray" in self._template: 311 self._areas = _areas_blue_gray(self) 312 self._spacing = _spacing_blue_gray(self) 313 self._colors = _colors_blue_gray 314 self._line_size = _linesize_blue_gray 315 elif "black_white" in self._template: 316 self._areas = _areas_black_white(self) 317 self._spacing = _spacing_black_white(self) 318 self._colors = _colors_black_white 319 self._line_size = _linesize_black_white 320 321 def _unicode_filter(self, code: int) -> int: 322 # Ignore Carriage Return characters and ® (superscript issues) 323 if code in {0xD, ord("®")}: 324 return None 325 # Correct some weird unicode stuffing choices 326 if code in {2}: 327 return ord("-") 328 if code in {61623, 61664}: 329 return ord("•") 330 return code 331 332 @cached_property 333 def identifier(self) -> str: 334 return self.text_in_named_area("id", check_length=False) 335 336 @cached_property 337 def top(self) -> str: 338 if self.index == 0: 339 return "Cover" 340 return self.text_in_named_area("top", check_length=False) 341 342 @cached_property 343 def is_toc(self) -> bool: 344 return _TOC_PAGE.fullmatch(self.top.strip()) is not None 345 346 def _link_target(self, char) -> str | None: 347 if char.objlink is not None: 348 # Cells of tables merged across pages keep the characters of their own page 349 text = char._page._link_texts.get(id(char.objlink), "") 350 if target := self.pdf.link_target(char.objlink, text): 351 return target 352 return None if char.weblink is None else char.weblink.url 353 354 def anchor_at(self, xpos: float | None, ypos: float | None) -> str: 355 """The HTML id of the link destination at this position.""" 356 return self._destination(xpos, ypos)[0] 357 358 def _destination(self, xpos: float | None, ypos: float | None) -> tuple[str, CharLine | None]: 359 """ 360 The HTML id of the heading, table or figure at this position. Other 361 destinations, like footnotes, get an id from their line, which is 362 returned too, so that it can be added to the HTML. Without a line 363 the destination falls back to the id of the page. 364 """ 365 if self.rotation: 366 # Like the characters, the position is rotated into the page orientation 367 ypos = None if xpos is None else self.height - xpos 368 if ypos is None: 369 return (f"page{self.number}", None) 370 y_em = self._spacing["y_em"] 371 # The destination is usually at the top of the line, sometimes a little above or below 372 lines = [line for line in self._content_lines if abs(line.bbox.top - ypos) <= 2 * y_em] 373 lines.sort(key=lambda line: abs(line.bbox.top - ypos)) 374 for line in lines: 375 if (anchor := self._line_id(line)) is not None: 376 return (anchor, None) 377 if lines: 378 return (f"page{self.number}-{round(lines[0].bbox.top)}", lines[0]) 379 return (f"page{self.number}", None) 380 381 def _line_id(self, line: CharLine) -> str | None: 382 """The id of a heading, table or figure starting with this line.""" 383 content, bold = line.content, "Bold" in line.chars[0].font 384 linesize = self._line_size(line) 385 # The same heading and caption detection as in ast_in_area 386 if ( 387 linesize.startswith("h1") 388 or ( 389 linesize.startswith("h") 390 and line.bbox.left < (self._spacing["x_content"] + 2 * self._spacing["x_em"]) 391 and bold 392 ) 393 or self._is_numbered_heading(line) 394 ): 395 if (match := re.match(r"^ *(\d+(?:\.\d+)*) *", content)) is not None: 396 return f"section{match.group(1)}" 397 elif bold and (match := re.match(r" *([Tt]able|[Ff]igure) ?(\d+)\.? ?", content)) is not None: 398 return f"{match.group(1).lower()}{match.group(2)}" 399 return None 400 401 def _is_numbered_heading(self, line: CharLine) -> bool: 402 """ 403 A bold line in the margin left of the text that starts with a section number like "30.4.2 Title" is a 404 heading, even when ST set it smaller than the other headings to fit a long title. 405 """ 406 return ( 407 line.bbox.left < self._spacing["x_content"] - self._spacing["x_em"] 408 and "Bold" in line.chars[0].font 409 and re.match(r" *\d+(\.\d+)+ +[A-Z]", line.content) is not None 410 ) 411 412 @cached_property 413 def named_ids(self) -> set[str]: 414 """The ids of all headings, tables and figures starting on this page.""" 415 return {anchor for line in self._content_lines if (anchor := self._line_id(line)) is not None} 416 417 @cached_property 418 def _link_texts(self) -> dict[int, str]: 419 """The text of each link on this page.""" 420 self._link_characters() 421 texts = defaultdict(str) 422 for char in self.chars: 423 if char.objlink is not None: 424 texts[id(char.objlink)] += chr(char.unicode) 425 texts = {key: " ".join(text.split()) for key, text in texts.items()} 426 # The lists of tables and figures only link the title and page, the number is in front of it on the line 427 for link in self.objlinks: 428 if not re.match(r"(Section|Table|Figure)\s+\d", texts.get(id(link), "")): 429 line = Rectangle(0, link.bbox.bottom, self.width, link.bbox.top) 430 if match := re.match(r" *((?:Table|Figure)\s+\d+)\.\s", self.text_in_area(line)): 431 texts[id(link)] = match.group(1) 432 return texts 433 434 @cached_property 435 def _content_lines(self) -> list[CharLine]: 436 # A page has many link destinations, its lines are only searched once 437 return [ 438 line for area in self._areas["content"] for line in self.charlines_in_area(area) if line.content.strip() 439 ] 440 441 @cached_property 442 def _line_anchors(self) -> dict[int, str]: 443 """The ids of the link destinations on this page by the characters of their lines.""" 444 anchors = {} 445 for location in self.pdf.destinations.get(self.index, ()): 446 anchor, line = self._destination(*location) 447 if line is not None: 448 anchors.update((id(c), anchor) for c in line.chars) 449 return anchors 450 451 @property 452 def content_ast(self) -> list: 453 ast = [] 454 with_graphics = True 455 if "DS" in self.pdf.name: 456 # FIXME: Terrible hack to get the ordering information table fixed 457 # Should be done in the AST as a rewrite similar to bit table rewrite with VirtualTable 458 order_page = next( 459 ( 460 item.page_index 461 for item in self.pdf.toc 462 if item.level == 0 and re.search("ordering +information|part +numbering", item.title, re.IGNORECASE) 463 ), 464 -1, 465 ) 466 with_graphics = order_page != self.index 467 for area in self._areas["content"]: 468 if self.is_toc: 469 ast.append(self.toc_in_area(area)) 470 else: 471 ast.append(self.ast_in_area(area, with_graphics=with_graphics)) 472 # Add a page node to the first leaf to keep track of where a page starts 473 first_leaf = next((n for n in iter(ast[0].descendants) if n.is_leaf), ast[0]) 474 # Destinations in figures or on lines without HTML element fall back to the page 475 used = {n._anchor for area in ast for n in area.descendants if getattr(n, "_anchor", None)} 476 anchors = sorted(set(self._line_anchors.values()) - used) 477 Node("page", parent=first_leaf, xpos=first_leaf.xpos, number=self.number, _anchors=anchors) 478 return ast 479 480 def _with_labels(self, area: Rectangle, bbox: Rectangle) -> Rectangle: 481 # Labels of bit diagrams end at their leader lines, so they stick out 482 # of the drawn graphics and would otherwise be glued into the text. 483 # Labels that overlap the graphics are part of the figure too. 484 x_em = self._spacing["x_em"] 485 # Captions are never labels, even where their subscripts reach into the graphics 486 captions = { 487 id(c) 488 for line in self.charlines_in_area(area) 489 if re.match(r"\s*(Figure|Table) \d+\.", "".join(c.char for c in line.chars)) 490 for c in line.chars 491 } 492 chars = [c for c in self.chars_in_area(area) if c.unicode not in {0x20, 0xA, 0xD} and id(c) not in captions] 493 graphics = bbox 494 while True: 495 grown = bbox 496 for c in chars: 497 # Labels can also stick out at the top or bottom of the graphics: 498 # their baseline or the top of their letters is inside of them. 499 # Captions just above the graphics only touch them with their 500 # descenders. Only the graphics count vertically, otherwise a 501 # label at the top would pull in the caption above it. 502 inside = graphics.bottom + 0.5 < c.origin.y < graphics.top - 0.5 or ( 503 graphics.bottom + 0.3 * (c.bbox.top - c.bbox.bottom) < c.bbox.top < graphics.top 504 ) 505 if inside and bbox.left - x_em <= c.bbox.right and c.bbox.left <= bbox.right + x_em: 506 grown = grown.joined(c.bbox) 507 if grown.isclose(bbox): 508 return bbox 509 bbox = grown 510 511 def graphics_in_area(self, area: Rectangle) -> list[Table | Figure]: 512 # Find all graphic clusters in this area 513 em = self._spacing["y_em"] 514 large_area = area.offset_x(em / 2) 515 graphic_clusters = self.graphic_clusters(lambda p: large_area.contains(p.bbox), em / 2) 516 # for bbox, paths in raw_graphic_clusters: 517 # # Some docs have large DRAFT chars in the background 518 # if any(path.fill == 0xe6e6e6ff and path.stroke == 0xff for path in paths): 519 # continue 520 # graphic_clusters.append((bbox, paths)) 521 522 # Find the captions and group them by y origin to catch side-by-side figures 523 ycaptions = defaultdict(list) 524 for line in self.charlines_in_area(area, lambda c: "Bold" in c.font): 525 for cluster in line.clusters(): 526 for phrase in [r"Figure \d+\.", r"Table \d+\."]: 527 if re.match(phrase, cluster.content): 528 ycaptions[int(round(cluster.bbox.y / em))].append((phrase, cluster.chars)) 529 ycaptions = [ycaptions[k] for k in sorted(ycaptions.keys(), key=lambda y: -y)] 530 531 # Now associate these captions with the graphics bboxes 532 categories = [] 533 for captions in ycaptions: 534 width = area.width / len(captions) 535 for ii, (phrase, chars) in enumerate(sorted(captions, key=lambda c: c[1][0].origin.x)): 536 left, right = area.left + ii * width, area.left + (ii + 1) * width 537 bottom, top, height = chars[0].bbox.bottom, chars[0].bbox.top, chars[0].height 538 539 # Find the graphic associated with this caption 540 graphic = next( 541 ((b, p) for b, p in graphic_clusters if b.bottom <= bottom and left <= b.left and b.right <= right), 542 None, 543 ) 544 if graphic is None: 545 _LOGGER.error(f"Graphic cluster not found for caption {''.join(c.char for c in chars)}") 546 continue 547 548 if self._template == "blue_gray": 549 # Search for all lines of the current caption with the same properties 550 cbbox = Rectangle(left, bottom, right, top) 551 cchars = self.chars_in_area(cbbox) 552 while True: 553 nbbox = Rectangle(left, max(graphic[0].top, cbbox.bottom - height), right, top) 554 nchars = self.chars_in_area(nbbox) 555 if len(cchars) >= len(nchars): 556 break 557 cbbox = nbbox 558 cchars = nchars 559 else: 560 cbbox = Rectangle(left, min(graphic[0].top, bottom), right, top) 561 562 otype = phrase.split(" ")[0].lower() 563 if "Figure" in phrase: 564 # Find all other graphics in the bounding box 565 gbbox = Rectangle(left, graphic[0].bottom, right, cbbox.bottom) 566 graphics = [] 567 for b, p in graphic_clusters: 568 if gbbox.overlaps(b): 569 graphics.append((b, p)) 570 for g in graphics: 571 graphic_clusters.remove(g) 572 gbbox = [cluster[0] for cluster in graphics] 573 gbbox = reduce(lambda r0, r1: r0.joined(r1), gbbox) 574 paths = [p for cluster in graphics for p in cluster[1]] 575 576 if self._template == "blue_gray": 577 # Search for characters below the graphics bbox, max 1 y_em 578 gbbox = Rectangle(left, gbbox.bottom, right, gbbox.bottom) 579 while True: 580 gbbox = Rectangle(left, gbbox.bottom - self._spacing["y_em"], right, gbbox.bottom) 581 if not self.chars_in_area(gbbox): 582 break 583 # Generate the new bounding box which includes the caption 584 gbbox = self._with_labels(area, Rectangle(left, gbbox.bottom, right, cbbox.bottom)) 585 elif "Table" in phrase: 586 graphic_clusters.remove(graphic) 587 gbbox, paths = graphic 588 if ( 589 self._template == "black_white" 590 and sum(1 for path in paths if path.count == 2) >= len(paths) / 2 591 ): 592 otype += "_lines" 593 categories.append((otype, cbbox, gbbox, paths)) 594 595 # Deal with the remaining graphic categories 596 for gbbox, paths in graphic_clusters: 597 if gbbox.width < self._spacing["x_em"] or gbbox.height < self._spacing["y_em"]: 598 continue 599 category = "" 600 if any(isinstance(p, Image) for p in paths): 601 category = "figure" 602 elif self._template == "blue_gray": 603 if all(self._colors(path.stroke) == "gray" or self._colors(path.fill) == "darkblue" for path in paths): 604 category = "table" 605 else: 606 category = "figure" 607 elif self._template == "black_white": 608 # Some tables are rendered explicitly with filled rectangular 609 # shapes with others are implicitly rendered with stroked lines 610 stroked_table_lines = sum(1 for path in paths if path.count == 2) >= len(paths) / 2 611 is_table = stroked_table_lines or all( 612 [any(p.isclose(pp) for pp in path.bbox.points) for p in path.points].count(True) 613 >= len(path.points) * 2 / 3 614 for path in paths 615 ) 616 if len(paths) > 1 and is_table: 617 category = "table" 618 if stroked_table_lines: 619 category += "_lines" 620 else: 621 category = "figure" 622 623 if "table" in category: 624 # Check if there are only numbers on top of the table 625 cbbox = Rectangle(gbbox.left, gbbox.top, gbbox.right, gbbox.top + self._spacing["y_em"]) 626 nchars = [c for c in self.chars_in_area(cbbox) if c.unicode not in {0x20, 0xA, 0xD}] 627 628 if nchars and sum(1 if c.char.isnumeric() else 0 for c in nchars) >= len(nchars) / 3: 629 # This is a register table with invisible top borders! 630 cbbox = Rectangle(gbbox.left, gbbox.top, gbbox.right, max(c.bbox.top for c in nchars)) 631 gbbox = Rectangle(gbbox.left, gbbox.bottom, gbbox.right, cbbox.top) 632 name = "register_" + category 633 else: 634 cbbox = None 635 name = category 636 categories.append((name, cbbox, gbbox, paths)) 637 else: 638 categories.append(("figure", None, self._with_labels(area, gbbox), paths)) 639 640 # Convert the objects into specialized classes 641 categories.sort(key=lambda o: (-o[2].y, o[2].x)) 642 objects = [] 643 for otype, caption_bbox, graphics_bbox, graphics_paths in categories: 644 if "figure" in otype: 645 figure = Figure(self, graphics_bbox, caption_bbox, graphics_paths) 646 objects.append(figure) 647 elif "table" in otype: 648 xlines, ylines, yhlines = [], [], [] 649 # Swatches of a color key "<square> = Same feature" are drawn left of a "=" that starts the line 650 swatches = [] 651 size = 2 * self._spacing["y_em"] 652 for line in self.charlines_in_area(graphics_bbox): 653 glyphs = [c for c in line.chars if c.unicode not in {0x20, 0xA, 0xD}] 654 for left, char in zip([None] + glyphs, glyphs): 655 if char.char == "=" and (left is None or char.bbox.left - left.bbox.right > size): 656 mid = char.bbox.midpoint.y 657 swatches.append( 658 Rectangle(char.bbox.left - size, mid - size / 2, char.bbox.left, mid + size / 2) 659 ) 660 for path in graphics_paths: 661 if any( 662 path.bbox.left > s.left - 1 663 and path.bbox.right < s.right + 1 664 and path.bbox.bottom > s.bottom - 1 665 and path.bbox.top < s.top + 1 666 for s in swatches 667 ): 668 continue 669 if self._template == "blue_gray" or "_lines" in otype: 670 if self._colors(path.stroke) == "gray" or "_lines" in otype: 671 # Intercell paths in gray 672 if len(path.lines) == 1: 673 line = path.lines[0] 674 if line.direction == line.Direction.VERTICAL: 675 xlines.append(line.specialize()) 676 elif line.direction == line.Direction.HORIZONTAL: 677 ylines.append(line.specialize()) 678 else: 679 _LOGGER.warn(f"Line not vertical or horizontal: {line}") 680 else: 681 _LOGGER.warn(f"Path too long: {path}") 682 elif self._colors(path.fill) == "darkblue": 683 # Add the bottom line of the dark blue header box as a very thick line 684 line = HLine(path.bbox.bottom, path.bbox.left, path.bbox.right, 5) 685 yhlines.append(line) 686 687 elif self._template == "black_white": 688 # Cell borders are lines and rectangles, glyph outlines of a watermark are not 689 if path.count > 6: 690 continue 691 bbox = path.bbox 692 is_vertical = bbox.width < bbox.height 693 width = bbox.width if is_vertical else bbox.height 694 length = bbox.height if is_vertical else bbox.width 695 if width <= self._spacing["x_em"] / 2: 696 if length >= self._spacing["y_em"] / 2: 697 if is_vertical: 698 line = VLine(bbox.midpoint.x, bbox.bottom, bbox.top, bbox.width) 699 xlines.append(line) 700 else: 701 line = HLine(bbox.midpoint.y, bbox.left, bbox.right, bbox.height) 702 ylines.append(line) 703 else: 704 # Split the rectangle into it's outline 705 xlines.append(VLine(bbox.left, bbox.bottom, bbox.top, 0.1)) 706 xlines.append(VLine(bbox.right, bbox.bottom, bbox.top, 0.1)) 707 ylines.append(HLine(bbox.bottom, bbox.left, bbox.right, 0.1)) 708 ylines.append(HLine(bbox.top, bbox.left, bbox.right, 0.1)) 709 if yhlines: 710 yhlines.sort(key=lambda line: line.p0.y) 711 ylines.append(yhlines[0]) 712 if not xlines or not ylines: 713 continue 714 table = Table(self, graphics_bbox, xlines, ylines, caption_bbox, is_register="register" in otype) 715 objects.append(table) 716 717 return objects 718 719 def toc_in_area(self, area: Rectangle) -> Node: 720 """ 721 Splits the entries of a table of contents or list of tables or figures 722 into their number, title and page number without the dot leaders. 723 Entries span several lines until the line with the page number, an 724 entry without page number continues on the next page. 725 """ 726 root = Node("area", obj=area, xpos=int(area.left), page=self) 727 # The characters of the entry text as (line, char, string) for the formatting 728 toc, lines, chars, text = None, [], [], "" 729 charlines = [line for line in self.charlines_in_area(area) if line.content.strip()] 730 # The page numbers are right aligned, the titles wrap before them 731 right_x = max((c.bbox.right for line in charlines for c in line.chars if c.char.strip()), default=0) 732 733 def _target(line): 734 if (target := _TOC_TARGET.search(text)) is None: 735 return None 736 # Usually dot leaders, but some have only one dot or none at all 737 if target.group(0).count(".") + target.group(0).count("…") >= 2: 738 return target 739 last = next(c for c in reversed(line.chars) if c.char.strip()) 740 if last.bbox.right >= right_x - self._spacing["x_em"] / 2: 741 return target 742 return None 743 744 def _entry(target): 745 nonlocal toc, lines, chars, text 746 if toc is None: 747 toc = Node("toc", parent=root, obj=lines[0], xpos=round(lines[0].bbox.left)) 748 start, end = 0, len(text) if target is None else target.start() 749 marker = None 750 if (match := _TOC_MARKER.match(text[:end])) is not None: 751 marker, start = match.group(1), match.end() 752 target = None if target is None else target.group(1) 753 Node( 754 "entry", 755 parent=toc, 756 obj=lines[0], 757 xpos=toc.xpos, 758 marker=marker, 759 title=text[start:end], 760 target=target, 761 _chars=chars[start:end], 762 ) 763 lines, chars, text = [], [], "" 764 765 for line in charlines: 766 content = line.content.strip() 767 linesize = self._line_size(line) 768 if not lines and linesize.startswith("h") and not _TOC_MARKER.match(content): 769 if _TOC_TARGET.search(content) is None: 770 # The title of the table of contents or of the lists 771 size = linesize[1] 772 xpos = round(line.bbox.left) 773 head = Node(f"head{size}", parent=root, obj=line, xpos=xpos, size=size, marker=None) 774 para = Node("para", parent=head, obj=line, xpos=xpos) 775 Node("line", parent=para, obj=line, xpos=xpos, start=0, str=content[:50]) 776 toc = None 777 continue 778 if lines and re.match(r"(Figure|Table) \d+\. ", content): 779 # The previous caption ends without right aligned page number 780 _entry(_TOC_TARGET.search(text) if re.search(r"\s\d+$", text) else None) 781 if len(lines) >= 5: 782 # Entries never get that long, this is the text after the table of contents 783 below = Rectangle(area.left, area.bottom, area.right, lines[0].bbox.top + 1) 784 for child in self.ast_in_area(below).children: 785 child.parent = root 786 return root 787 lines.append(line) 788 # Long part numbers wrap after a slash without space 789 if chars and chars[-1][2] != "/": 790 chars.append(chars[-1][:2] + (" ",)) 791 chars += list_strip([(line, c, s) for c in line.chars for s in c.char], lambda c: not c[2].strip()) 792 text = "".join(c[2] for c in chars) 793 if (target := _target(line)) is not None: 794 _entry(target) 795 if lines: 796 _entry(None) 797 return root 798 799 def ast_in_area( 800 self, 801 area: Rectangle, 802 with_graphics: bool = True, 803 ignore_xpos: bool = False, 804 with_bits: bool = True, 805 with_notes: bool = True, 806 ) -> Node: 807 x_em = self._spacing["x_em"] 808 spacing_content = self._spacing["x_content"] 809 lh_factor = self._spacing["lh"] 810 # spacing_y = self._spacing["y_em"] 811 root = Node("area", obj=area, xpos=int(area.left), page=self) 812 813 def unindent(_xpos, _current, _newlines=1): 814 current = _current 815 # Check if we need to unindent the current node 816 while (_xpos - current.xpos) < -x_em and current.parent is not None and not ignore_xpos: 817 current = current.parent 818 if _newlines >= 2 and current.name == "para": 819 current = current.parent 820 return current 821 822 def parent_name(current): 823 return "" if current.parent is None else current.parent.name 824 825 current = root 826 ypos = area.top 827 for obj in self.objects_in_area(area, with_graphics): 828 xpos = round(obj.bbox.left) 829 830 # Tables should remain in their current hierarchy regardless of indentation 831 if isinstance(obj, (Table, Figure)): 832 current = next((c for c in current.iter_path_reverse() if c.name.startswith("head")), root) 833 name = "figure" if isinstance(obj, Figure) else "table" 834 Node( 835 name, 836 parent=current, 837 obj=obj, 838 xpos=xpos, 839 number=-1, 840 _type=obj._type, 841 ) 842 ypos = obj.bbox.bottom 843 844 # Lines of text need to be carefully checked for indentation 845 elif isinstance(obj, CharLine): 846 newlines = round((ypos - obj.origin) / (lh_factor * obj.height)) 847 content = obj.content 848 lcontent = content.lstrip() 849 content_start = 0 850 linesize = self._line_size(obj) 851 852 # Check when the note has finished (=> paragraphs without italic) 853 if parent_name(current) == "note" and ( 854 (current.parent.type == "note" and not obj.contains_font(current.parent._font)) 855 or (current.parent.type in {"caution", "warning"} and newlines >= 2) 856 ): 857 current = current.parent.parent 858 859 # Check when the list ends into something indented far too right 860 elif parent_name(current).startswith("list") and (xpos - current.xpos) >= 2 * x_em: 861 current = current.parent.parent 862 863 # print(obj.fonts, ypos, xpos, current.xpos, f"{obj.height:.2f}", content) 864 865 # Check if line is a heading, which may be multi-line, so we must 866 # be careful not to nest them, but group them properly 867 # Headings are always inserted into the root note! 868 if ( 869 linesize.startswith("h1") 870 or ( 871 linesize.startswith("h") and xpos < (spacing_content + 2 * x_em) and "Bold" in obj.chars[0].font 872 ) 873 or (with_graphics and self._is_numbered_heading(obj)) 874 ): 875 if (match := re.match(r"^ *(\d+(?:\.\d+)*) *", content)) is not None: 876 start = min(len(match.group(0)), len(obj.chars) - 1) 877 marker = match.group(1) 878 size = min(marker.count(".") + 2, 6) 879 else: 880 start = 0 881 marker = None 882 size = linesize[1] 883 name = f"head{size}" 884 # Check if we're already parsing a heading, do not split into two 885 if parent_name(current) != name or newlines > 2: 886 content_start = start 887 xpos = round(obj.chars[content_start].bbox.left) 888 current = Node(name, parent=root, obj=obj, xpos=xpos, size=size, marker=marker) 889 current = Node("para", parent=current, obj=obj, xpos=current.xpos) 890 891 # Check if the line is a note and deal with the indentation correctly 892 elif ( 893 with_notes and (match := re.match(r" *([Nn]ote|[Cc]aution|[Ww]arning):? \d?", content)) is not None 894 ): 895 content_start = min(len(match.group(0)), len(obj.chars) - 1) 896 # print(obj.fonts) 897 # Correct xposition only if the Note: string is very far left 898 if xpos + 4 * x_em <= current.xpos: 899 xpos = round(obj.chars[content_start].bbox.left) 900 # Prevent nesting of notes, they should only be listed 901 if parent_name(current) == "note": 902 current = current.parent.parent 903 current = unindent(xpos, current, 2) 904 current = Node( 905 "note", 906 parent=current, 907 obj=obj, 908 xpos=xpos, 909 type=match.group(1).lower(), 910 _font=obj.chars[content_start].font, 911 ) 912 current = Node("para", parent=current, obj=obj, xpos=current.xpos) 913 914 # Check if line is Table or Figure caption 915 elif with_graphics and ( 916 (match := re.match(r" *([Tt]able|[Ff]igure) ?(\d+)\.? ?", content)) is not None 917 and "Bold" in obj.chars[0].font 918 ): 919 content_start = min(len(match.group(0)), len(obj.chars) - 1) 920 current = next((c for c in current.iter_path_reverse() if c.name.startswith("head")), root) 921 current = Node( 922 "caption", 923 parent=current, 924 obj=obj, 925 xpos=xpos, 926 _type=match.group(1).lower(), 927 number=int(match.group(2)), 928 ) 929 current = Node("para", parent=current, obj=obj, xpos=current.xpos) 930 931 # Check if line is list and group them according to indentation 932 elif (match := re.match(r"^ *([•–]) ..|^ *(\d+)\. ..|^ *([a-z])\) ?..", content)) is not None: 933 current = unindent(xpos, current, newlines) 934 content_start = len(match.group(0)) - 2 935 xpos = round(obj.chars[content_start].bbox.left) 936 name = "listb" 937 value = lcontent[0] 938 if value in {"–", "-"}: 939 name = "lists" 940 elif value.isalpha(): 941 name = "lista" 942 elif value.isnumeric(): 943 name = "listn" 944 value = int(match.group(2)) 945 current = Node(name, parent=current, obj=obj, xpos=xpos, value=value) 946 current = Node("para", parent=current, obj=obj, xpos=current.xpos) 947 948 # Check if line is a register bit definition 949 elif ( 950 with_bits 951 and re.match(r" *([Bb]ytes? *.+? *)?B[uio]ts? *\d+", content) is not None 952 # A sentence starting with "Bits" inside the description column is not a new bit 953 and not any(c.name == "bit" and xpos >= c._middle - x_em for c in current.iter_path_reverse()) 954 ): 955 if obj.contains_font("Bold"): 956 # Use the bold character as delimiter 957 content_start = next(xi for xi, c in enumerate(obj.chars) if "Bold" in c.font) 958 else: 959 # Default back to the regex 960 if "Reserved" not in content: 961 _LOGGER.warning( 962 f"Fallback to Regex length for Bit pattern '{content}'!\nFonts: {obj.fonts}" 963 ) 964 content_start = re.match( 965 r" *([Bb]ytes? *.+? *)?(B[uio]t)( *\d+:?|s *(\d+ *([:-] *\d+ *)? *,? *)+) *", content 966 ) 967 if content_start is None: 968 _LOGGER.error(f"Unable to match Bit regex at all! '{content}'!") 969 content_start = 0 970 else: 971 content_start = len(content_start.group(0)) 972 if not content_start: 973 _LOGGER.error(f"Missing content start (=0)! '{content}'!") 974 content_start = min(content_start, len(obj.chars) - 1) 975 976 current = next((c for c in current.iter_path_reverse() if c.name.startswith("head")), root) 977 middle = obj.chars[content_start].bbox.left 978 xpos = round(middle) 979 current = Node( 980 "bit", 981 parent=current, 982 obj=obj, 983 xpos=xpos, 984 _page=self, 985 _middle=middle, 986 _left=area.left, 987 _right=area.right, 988 ) 989 current = Node("para", parent=current, obj=obj, xpos=current.xpos) 990 991 # Check if this is a new paragraph 992 elif newlines >= 2 or current.name not in {"para"}: 993 # Fix issues where notes are reflowing back left of Note: text 994 if parent_name(current) in {"note"}: 995 if xpos < current.parent.xpos: 996 xpos = current.parent.xpos 997 # Prevent multiline 998 current = unindent(xpos, current, newlines) 999 current = Node("para", parent=current, obj=obj, xpos=xpos if current.is_root else current.xpos) 1000 1001 elif parent_name(current) not in {"caption", "bit", "area"}: 1002 current = unindent(xpos, current, newlines) 1003 # A line after a list unindents out of the list, but only a paragraph is formatted 1004 if current.name != "para": 1005 current = Node("para", parent=current, obj=obj, xpos=xpos if current.is_root else current.xpos) 1006 1007 # Add the actual line 1008 anchor = next((a for c in obj.chars if (a := self._line_anchors.get(id(c)))), None) 1009 Node( 1010 "line", 1011 parent=current, 1012 obj=obj, 1013 xpos=xpos, 1014 start=content_start, 1015 str=content[content_start:50], 1016 _anchor=anchor, 1017 ) 1018 1019 ypos = obj.origin 1020 1021 return root 1022 1023 def __repr__(self) -> str: 1024 return f"StmPage({self.number})"
This class provides low-level access to graphics and characters of the page and allows searching for characters in an area instead of just text.
299 def __init__(self, document, index: int): 300 super().__init__(document, index) 301 producer = self.pdf.metadata.get("Producer", "").lower() 302 self._template = "black_white" 303 if "acrobat" in producer or "adobe" in producer: 304 pass 305 elif "antenna" in producer: 306 self._template = "blue_gray" 307 else: 308 _LOGGER.error(f"Unknown page template! Defaulting to Black/White template. '{producer}'") 309 310 if "blue_gray" in self._template: 311 self._areas = _areas_blue_gray(self) 312 self._spacing = _spacing_blue_gray(self) 313 self._colors = _colors_blue_gray 314 self._line_size = _linesize_blue_gray 315 elif "black_white" in self._template: 316 self._areas = _areas_black_white(self) 317 self._spacing = _spacing_black_white(self) 318 self._colors = _colors_black_white 319 self._line_size = _linesize_black_white
Parameters
- document: a PDF document.
- index: 0-index page number.
354 def anchor_at(self, xpos: float | None, ypos: float | None) -> str: 355 """The HTML id of the link destination at this position.""" 356 return self._destination(xpos, ypos)[0]
The HTML id of the link destination at this position.
412 @cached_property 413 def named_ids(self) -> set[str]: 414 """The ids of all headings, tables and figures starting on this page.""" 415 return {anchor for line in self._content_lines if (anchor := self._line_id(line)) is not None}
The ids of all headings, tables and figures starting on this page.
451 @property 452 def content_ast(self) -> list: 453 ast = [] 454 with_graphics = True 455 if "DS" in self.pdf.name: 456 # FIXME: Terrible hack to get the ordering information table fixed 457 # Should be done in the AST as a rewrite similar to bit table rewrite with VirtualTable 458 order_page = next( 459 ( 460 item.page_index 461 for item in self.pdf.toc 462 if item.level == 0 and re.search("ordering +information|part +numbering", item.title, re.IGNORECASE) 463 ), 464 -1, 465 ) 466 with_graphics = order_page != self.index 467 for area in self._areas["content"]: 468 if self.is_toc: 469 ast.append(self.toc_in_area(area)) 470 else: 471 ast.append(self.ast_in_area(area, with_graphics=with_graphics)) 472 # Add a page node to the first leaf to keep track of where a page starts 473 first_leaf = next((n for n in iter(ast[0].descendants) if n.is_leaf), ast[0]) 474 # Destinations in figures or on lines without HTML element fall back to the page 475 used = {n._anchor for area in ast for n in area.descendants if getattr(n, "_anchor", None)} 476 anchors = sorted(set(self._line_anchors.values()) - used) 477 Node("page", parent=first_leaf, xpos=first_leaf.xpos, number=self.number, _anchors=anchors) 478 return ast
The abstract syntax trees in the content area.
511 def graphics_in_area(self, area: Rectangle) -> list[Table | Figure]: 512 # Find all graphic clusters in this area 513 em = self._spacing["y_em"] 514 large_area = area.offset_x(em / 2) 515 graphic_clusters = self.graphic_clusters(lambda p: large_area.contains(p.bbox), em / 2) 516 # for bbox, paths in raw_graphic_clusters: 517 # # Some docs have large DRAFT chars in the background 518 # if any(path.fill == 0xe6e6e6ff and path.stroke == 0xff for path in paths): 519 # continue 520 # graphic_clusters.append((bbox, paths)) 521 522 # Find the captions and group them by y origin to catch side-by-side figures 523 ycaptions = defaultdict(list) 524 for line in self.charlines_in_area(area, lambda c: "Bold" in c.font): 525 for cluster in line.clusters(): 526 for phrase in [r"Figure \d+\.", r"Table \d+\."]: 527 if re.match(phrase, cluster.content): 528 ycaptions[int(round(cluster.bbox.y / em))].append((phrase, cluster.chars)) 529 ycaptions = [ycaptions[k] for k in sorted(ycaptions.keys(), key=lambda y: -y)] 530 531 # Now associate these captions with the graphics bboxes 532 categories = [] 533 for captions in ycaptions: 534 width = area.width / len(captions) 535 for ii, (phrase, chars) in enumerate(sorted(captions, key=lambda c: c[1][0].origin.x)): 536 left, right = area.left + ii * width, area.left + (ii + 1) * width 537 bottom, top, height = chars[0].bbox.bottom, chars[0].bbox.top, chars[0].height 538 539 # Find the graphic associated with this caption 540 graphic = next( 541 ((b, p) for b, p in graphic_clusters if b.bottom <= bottom and left <= b.left and b.right <= right), 542 None, 543 ) 544 if graphic is None: 545 _LOGGER.error(f"Graphic cluster not found for caption {''.join(c.char for c in chars)}") 546 continue 547 548 if self._template == "blue_gray": 549 # Search for all lines of the current caption with the same properties 550 cbbox = Rectangle(left, bottom, right, top) 551 cchars = self.chars_in_area(cbbox) 552 while True: 553 nbbox = Rectangle(left, max(graphic[0].top, cbbox.bottom - height), right, top) 554 nchars = self.chars_in_area(nbbox) 555 if len(cchars) >= len(nchars): 556 break 557 cbbox = nbbox 558 cchars = nchars 559 else: 560 cbbox = Rectangle(left, min(graphic[0].top, bottom), right, top) 561 562 otype = phrase.split(" ")[0].lower() 563 if "Figure" in phrase: 564 # Find all other graphics in the bounding box 565 gbbox = Rectangle(left, graphic[0].bottom, right, cbbox.bottom) 566 graphics = [] 567 for b, p in graphic_clusters: 568 if gbbox.overlaps(b): 569 graphics.append((b, p)) 570 for g in graphics: 571 graphic_clusters.remove(g) 572 gbbox = [cluster[0] for cluster in graphics] 573 gbbox = reduce(lambda r0, r1: r0.joined(r1), gbbox) 574 paths = [p for cluster in graphics for p in cluster[1]] 575 576 if self._template == "blue_gray": 577 # Search for characters below the graphics bbox, max 1 y_em 578 gbbox = Rectangle(left, gbbox.bottom, right, gbbox.bottom) 579 while True: 580 gbbox = Rectangle(left, gbbox.bottom - self._spacing["y_em"], right, gbbox.bottom) 581 if not self.chars_in_area(gbbox): 582 break 583 # Generate the new bounding box which includes the caption 584 gbbox = self._with_labels(area, Rectangle(left, gbbox.bottom, right, cbbox.bottom)) 585 elif "Table" in phrase: 586 graphic_clusters.remove(graphic) 587 gbbox, paths = graphic 588 if ( 589 self._template == "black_white" 590 and sum(1 for path in paths if path.count == 2) >= len(paths) / 2 591 ): 592 otype += "_lines" 593 categories.append((otype, cbbox, gbbox, paths)) 594 595 # Deal with the remaining graphic categories 596 for gbbox, paths in graphic_clusters: 597 if gbbox.width < self._spacing["x_em"] or gbbox.height < self._spacing["y_em"]: 598 continue 599 category = "" 600 if any(isinstance(p, Image) for p in paths): 601 category = "figure" 602 elif self._template == "blue_gray": 603 if all(self._colors(path.stroke) == "gray" or self._colors(path.fill) == "darkblue" for path in paths): 604 category = "table" 605 else: 606 category = "figure" 607 elif self._template == "black_white": 608 # Some tables are rendered explicitly with filled rectangular 609 # shapes with others are implicitly rendered with stroked lines 610 stroked_table_lines = sum(1 for path in paths if path.count == 2) >= len(paths) / 2 611 is_table = stroked_table_lines or all( 612 [any(p.isclose(pp) for pp in path.bbox.points) for p in path.points].count(True) 613 >= len(path.points) * 2 / 3 614 for path in paths 615 ) 616 if len(paths) > 1 and is_table: 617 category = "table" 618 if stroked_table_lines: 619 category += "_lines" 620 else: 621 category = "figure" 622 623 if "table" in category: 624 # Check if there are only numbers on top of the table 625 cbbox = Rectangle(gbbox.left, gbbox.top, gbbox.right, gbbox.top + self._spacing["y_em"]) 626 nchars = [c for c in self.chars_in_area(cbbox) if c.unicode not in {0x20, 0xA, 0xD}] 627 628 if nchars and sum(1 if c.char.isnumeric() else 0 for c in nchars) >= len(nchars) / 3: 629 # This is a register table with invisible top borders! 630 cbbox = Rectangle(gbbox.left, gbbox.top, gbbox.right, max(c.bbox.top for c in nchars)) 631 gbbox = Rectangle(gbbox.left, gbbox.bottom, gbbox.right, cbbox.top) 632 name = "register_" + category 633 else: 634 cbbox = None 635 name = category 636 categories.append((name, cbbox, gbbox, paths)) 637 else: 638 categories.append(("figure", None, self._with_labels(area, gbbox), paths)) 639 640 # Convert the objects into specialized classes 641 categories.sort(key=lambda o: (-o[2].y, o[2].x)) 642 objects = [] 643 for otype, caption_bbox, graphics_bbox, graphics_paths in categories: 644 if "figure" in otype: 645 figure = Figure(self, graphics_bbox, caption_bbox, graphics_paths) 646 objects.append(figure) 647 elif "table" in otype: 648 xlines, ylines, yhlines = [], [], [] 649 # Swatches of a color key "<square> = Same feature" are drawn left of a "=" that starts the line 650 swatches = [] 651 size = 2 * self._spacing["y_em"] 652 for line in self.charlines_in_area(graphics_bbox): 653 glyphs = [c for c in line.chars if c.unicode not in {0x20, 0xA, 0xD}] 654 for left, char in zip([None] + glyphs, glyphs): 655 if char.char == "=" and (left is None or char.bbox.left - left.bbox.right > size): 656 mid = char.bbox.midpoint.y 657 swatches.append( 658 Rectangle(char.bbox.left - size, mid - size / 2, char.bbox.left, mid + size / 2) 659 ) 660 for path in graphics_paths: 661 if any( 662 path.bbox.left > s.left - 1 663 and path.bbox.right < s.right + 1 664 and path.bbox.bottom > s.bottom - 1 665 and path.bbox.top < s.top + 1 666 for s in swatches 667 ): 668 continue 669 if self._template == "blue_gray" or "_lines" in otype: 670 if self._colors(path.stroke) == "gray" or "_lines" in otype: 671 # Intercell paths in gray 672 if len(path.lines) == 1: 673 line = path.lines[0] 674 if line.direction == line.Direction.VERTICAL: 675 xlines.append(line.specialize()) 676 elif line.direction == line.Direction.HORIZONTAL: 677 ylines.append(line.specialize()) 678 else: 679 _LOGGER.warn(f"Line not vertical or horizontal: {line}") 680 else: 681 _LOGGER.warn(f"Path too long: {path}") 682 elif self._colors(path.fill) == "darkblue": 683 # Add the bottom line of the dark blue header box as a very thick line 684 line = HLine(path.bbox.bottom, path.bbox.left, path.bbox.right, 5) 685 yhlines.append(line) 686 687 elif self._template == "black_white": 688 # Cell borders are lines and rectangles, glyph outlines of a watermark are not 689 if path.count > 6: 690 continue 691 bbox = path.bbox 692 is_vertical = bbox.width < bbox.height 693 width = bbox.width if is_vertical else bbox.height 694 length = bbox.height if is_vertical else bbox.width 695 if width <= self._spacing["x_em"] / 2: 696 if length >= self._spacing["y_em"] / 2: 697 if is_vertical: 698 line = VLine(bbox.midpoint.x, bbox.bottom, bbox.top, bbox.width) 699 xlines.append(line) 700 else: 701 line = HLine(bbox.midpoint.y, bbox.left, bbox.right, bbox.height) 702 ylines.append(line) 703 else: 704 # Split the rectangle into it's outline 705 xlines.append(VLine(bbox.left, bbox.bottom, bbox.top, 0.1)) 706 xlines.append(VLine(bbox.right, bbox.bottom, bbox.top, 0.1)) 707 ylines.append(HLine(bbox.bottom, bbox.left, bbox.right, 0.1)) 708 ylines.append(HLine(bbox.top, bbox.left, bbox.right, 0.1)) 709 if yhlines: 710 yhlines.sort(key=lambda line: line.p0.y) 711 ylines.append(yhlines[0]) 712 if not xlines or not ylines: 713 continue 714 table = Table(self, graphics_bbox, xlines, ylines, caption_bbox, is_register="register" in otype) 715 objects.append(table) 716 717 return objects
Find all tables and figures in this area.
Parameters
- area: area to search for graphics.
Returns
list of tables and figures.
719 def toc_in_area(self, area: Rectangle) -> Node: 720 """ 721 Splits the entries of a table of contents or list of tables or figures 722 into their number, title and page number without the dot leaders. 723 Entries span several lines until the line with the page number, an 724 entry without page number continues on the next page. 725 """ 726 root = Node("area", obj=area, xpos=int(area.left), page=self) 727 # The characters of the entry text as (line, char, string) for the formatting 728 toc, lines, chars, text = None, [], [], "" 729 charlines = [line for line in self.charlines_in_area(area) if line.content.strip()] 730 # The page numbers are right aligned, the titles wrap before them 731 right_x = max((c.bbox.right for line in charlines for c in line.chars if c.char.strip()), default=0) 732 733 def _target(line): 734 if (target := _TOC_TARGET.search(text)) is None: 735 return None 736 # Usually dot leaders, but some have only one dot or none at all 737 if target.group(0).count(".") + target.group(0).count("…") >= 2: 738 return target 739 last = next(c for c in reversed(line.chars) if c.char.strip()) 740 if last.bbox.right >= right_x - self._spacing["x_em"] / 2: 741 return target 742 return None 743 744 def _entry(target): 745 nonlocal toc, lines, chars, text 746 if toc is None: 747 toc = Node("toc", parent=root, obj=lines[0], xpos=round(lines[0].bbox.left)) 748 start, end = 0, len(text) if target is None else target.start() 749 marker = None 750 if (match := _TOC_MARKER.match(text[:end])) is not None: 751 marker, start = match.group(1), match.end() 752 target = None if target is None else target.group(1) 753 Node( 754 "entry", 755 parent=toc, 756 obj=lines[0], 757 xpos=toc.xpos, 758 marker=marker, 759 title=text[start:end], 760 target=target, 761 _chars=chars[start:end], 762 ) 763 lines, chars, text = [], [], "" 764 765 for line in charlines: 766 content = line.content.strip() 767 linesize = self._line_size(line) 768 if not lines and linesize.startswith("h") and not _TOC_MARKER.match(content): 769 if _TOC_TARGET.search(content) is None: 770 # The title of the table of contents or of the lists 771 size = linesize[1] 772 xpos = round(line.bbox.left) 773 head = Node(f"head{size}", parent=root, obj=line, xpos=xpos, size=size, marker=None) 774 para = Node("para", parent=head, obj=line, xpos=xpos) 775 Node("line", parent=para, obj=line, xpos=xpos, start=0, str=content[:50]) 776 toc = None 777 continue 778 if lines and re.match(r"(Figure|Table) \d+\. ", content): 779 # The previous caption ends without right aligned page number 780 _entry(_TOC_TARGET.search(text) if re.search(r"\s\d+$", text) else None) 781 if len(lines) >= 5: 782 # Entries never get that long, this is the text after the table of contents 783 below = Rectangle(area.left, area.bottom, area.right, lines[0].bbox.top + 1) 784 for child in self.ast_in_area(below).children: 785 child.parent = root 786 return root 787 lines.append(line) 788 # Long part numbers wrap after a slash without space 789 if chars and chars[-1][2] != "/": 790 chars.append(chars[-1][:2] + (" ",)) 791 chars += list_strip([(line, c, s) for c in line.chars for s in c.char], lambda c: not c[2].strip()) 792 text = "".join(c[2] for c in chars) 793 if (target := _target(line)) is not None: 794 _entry(target) 795 if lines: 796 _entry(None) 797 return root
Splits the entries of a table of contents or list of tables or figures into their number, title and page number without the dot leaders. Entries span several lines until the line with the page number, an entry without page number continues on the next page.
799 def ast_in_area( 800 self, 801 area: Rectangle, 802 with_graphics: bool = True, 803 ignore_xpos: bool = False, 804 with_bits: bool = True, 805 with_notes: bool = True, 806 ) -> Node: 807 x_em = self._spacing["x_em"] 808 spacing_content = self._spacing["x_content"] 809 lh_factor = self._spacing["lh"] 810 # spacing_y = self._spacing["y_em"] 811 root = Node("area", obj=area, xpos=int(area.left), page=self) 812 813 def unindent(_xpos, _current, _newlines=1): 814 current = _current 815 # Check if we need to unindent the current node 816 while (_xpos - current.xpos) < -x_em and current.parent is not None and not ignore_xpos: 817 current = current.parent 818 if _newlines >= 2 and current.name == "para": 819 current = current.parent 820 return current 821 822 def parent_name(current): 823 return "" if current.parent is None else current.parent.name 824 825 current = root 826 ypos = area.top 827 for obj in self.objects_in_area(area, with_graphics): 828 xpos = round(obj.bbox.left) 829 830 # Tables should remain in their current hierarchy regardless of indentation 831 if isinstance(obj, (Table, Figure)): 832 current = next((c for c in current.iter_path_reverse() if c.name.startswith("head")), root) 833 name = "figure" if isinstance(obj, Figure) else "table" 834 Node( 835 name, 836 parent=current, 837 obj=obj, 838 xpos=xpos, 839 number=-1, 840 _type=obj._type, 841 ) 842 ypos = obj.bbox.bottom 843 844 # Lines of text need to be carefully checked for indentation 845 elif isinstance(obj, CharLine): 846 newlines = round((ypos - obj.origin) / (lh_factor * obj.height)) 847 content = obj.content 848 lcontent = content.lstrip() 849 content_start = 0 850 linesize = self._line_size(obj) 851 852 # Check when the note has finished (=> paragraphs without italic) 853 if parent_name(current) == "note" and ( 854 (current.parent.type == "note" and not obj.contains_font(current.parent._font)) 855 or (current.parent.type in {"caution", "warning"} and newlines >= 2) 856 ): 857 current = current.parent.parent 858 859 # Check when the list ends into something indented far too right 860 elif parent_name(current).startswith("list") and (xpos - current.xpos) >= 2 * x_em: 861 current = current.parent.parent 862 863 # print(obj.fonts, ypos, xpos, current.xpos, f"{obj.height:.2f}", content) 864 865 # Check if line is a heading, which may be multi-line, so we must 866 # be careful not to nest them, but group them properly 867 # Headings are always inserted into the root note! 868 if ( 869 linesize.startswith("h1") 870 or ( 871 linesize.startswith("h") and xpos < (spacing_content + 2 * x_em) and "Bold" in obj.chars[0].font 872 ) 873 or (with_graphics and self._is_numbered_heading(obj)) 874 ): 875 if (match := re.match(r"^ *(\d+(?:\.\d+)*) *", content)) is not None: 876 start = min(len(match.group(0)), len(obj.chars) - 1) 877 marker = match.group(1) 878 size = min(marker.count(".") + 2, 6) 879 else: 880 start = 0 881 marker = None 882 size = linesize[1] 883 name = f"head{size}" 884 # Check if we're already parsing a heading, do not split into two 885 if parent_name(current) != name or newlines > 2: 886 content_start = start 887 xpos = round(obj.chars[content_start].bbox.left) 888 current = Node(name, parent=root, obj=obj, xpos=xpos, size=size, marker=marker) 889 current = Node("para", parent=current, obj=obj, xpos=current.xpos) 890 891 # Check if the line is a note and deal with the indentation correctly 892 elif ( 893 with_notes and (match := re.match(r" *([Nn]ote|[Cc]aution|[Ww]arning):? \d?", content)) is not None 894 ): 895 content_start = min(len(match.group(0)), len(obj.chars) - 1) 896 # print(obj.fonts) 897 # Correct xposition only if the Note: string is very far left 898 if xpos + 4 * x_em <= current.xpos: 899 xpos = round(obj.chars[content_start].bbox.left) 900 # Prevent nesting of notes, they should only be listed 901 if parent_name(current) == "note": 902 current = current.parent.parent 903 current = unindent(xpos, current, 2) 904 current = Node( 905 "note", 906 parent=current, 907 obj=obj, 908 xpos=xpos, 909 type=match.group(1).lower(), 910 _font=obj.chars[content_start].font, 911 ) 912 current = Node("para", parent=current, obj=obj, xpos=current.xpos) 913 914 # Check if line is Table or Figure caption 915 elif with_graphics and ( 916 (match := re.match(r" *([Tt]able|[Ff]igure) ?(\d+)\.? ?", content)) is not None 917 and "Bold" in obj.chars[0].font 918 ): 919 content_start = min(len(match.group(0)), len(obj.chars) - 1) 920 current = next((c for c in current.iter_path_reverse() if c.name.startswith("head")), root) 921 current = Node( 922 "caption", 923 parent=current, 924 obj=obj, 925 xpos=xpos, 926 _type=match.group(1).lower(), 927 number=int(match.group(2)), 928 ) 929 current = Node("para", parent=current, obj=obj, xpos=current.xpos) 930 931 # Check if line is list and group them according to indentation 932 elif (match := re.match(r"^ *([•–]) ..|^ *(\d+)\. ..|^ *([a-z])\) ?..", content)) is not None: 933 current = unindent(xpos, current, newlines) 934 content_start = len(match.group(0)) - 2 935 xpos = round(obj.chars[content_start].bbox.left) 936 name = "listb" 937 value = lcontent[0] 938 if value in {"–", "-"}: 939 name = "lists" 940 elif value.isalpha(): 941 name = "lista" 942 elif value.isnumeric(): 943 name = "listn" 944 value = int(match.group(2)) 945 current = Node(name, parent=current, obj=obj, xpos=xpos, value=value) 946 current = Node("para", parent=current, obj=obj, xpos=current.xpos) 947 948 # Check if line is a register bit definition 949 elif ( 950 with_bits 951 and re.match(r" *([Bb]ytes? *.+? *)?B[uio]ts? *\d+", content) is not None 952 # A sentence starting with "Bits" inside the description column is not a new bit 953 and not any(c.name == "bit" and xpos >= c._middle - x_em for c in current.iter_path_reverse()) 954 ): 955 if obj.contains_font("Bold"): 956 # Use the bold character as delimiter 957 content_start = next(xi for xi, c in enumerate(obj.chars) if "Bold" in c.font) 958 else: 959 # Default back to the regex 960 if "Reserved" not in content: 961 _LOGGER.warning( 962 f"Fallback to Regex length for Bit pattern '{content}'!\nFonts: {obj.fonts}" 963 ) 964 content_start = re.match( 965 r" *([Bb]ytes? *.+? *)?(B[uio]t)( *\d+:?|s *(\d+ *([:-] *\d+ *)? *,? *)+) *", content 966 ) 967 if content_start is None: 968 _LOGGER.error(f"Unable to match Bit regex at all! '{content}'!") 969 content_start = 0 970 else: 971 content_start = len(content_start.group(0)) 972 if not content_start: 973 _LOGGER.error(f"Missing content start (=0)! '{content}'!") 974 content_start = min(content_start, len(obj.chars) - 1) 975 976 current = next((c for c in current.iter_path_reverse() if c.name.startswith("head")), root) 977 middle = obj.chars[content_start].bbox.left 978 xpos = round(middle) 979 current = Node( 980 "bit", 981 parent=current, 982 obj=obj, 983 xpos=xpos, 984 _page=self, 985 _middle=middle, 986 _left=area.left, 987 _right=area.right, 988 ) 989 current = Node("para", parent=current, obj=obj, xpos=current.xpos) 990 991 # Check if this is a new paragraph 992 elif newlines >= 2 or current.name not in {"para"}: 993 # Fix issues where notes are reflowing back left of Note: text 994 if parent_name(current) in {"note"}: 995 if xpos < current.parent.xpos: 996 xpos = current.parent.xpos 997 # Prevent multiline 998 current = unindent(xpos, current, newlines) 999 current = Node("para", parent=current, obj=obj, xpos=xpos if current.is_root else current.xpos) 1000 1001 elif parent_name(current) not in {"caption", "bit", "area"}: 1002 current = unindent(xpos, current, newlines) 1003 # A line after a list unindents out of the list, but only a paragraph is formatted 1004 if current.name != "para": 1005 current = Node("para", parent=current, obj=obj, xpos=xpos if current.is_root else current.xpos) 1006 1007 # Add the actual line 1008 anchor = next((a for c in obj.chars if (a := self._line_anchors.get(id(c)))), None) 1009 Node( 1010 "line", 1011 parent=current, 1012 obj=obj, 1013 xpos=xpos, 1014 start=content_start, 1015 str=content[content_start:50], 1016 _anchor=anchor, 1017 ) 1018 1019 ypos = obj.origin 1020 1021 return root
Convert the area content into an abstract syntax tree.
Parameters
- area: area to search for content.
- with_graphics: including graphics in the area.
Returns
An abstract syntax tree including the content formatting.
Inherited Members
- modm_data.pdf2html.page.Page
- is_relevant
- text_in_named_area
- charlines_in_area
- graphic_bboxes_in_area
- objects_in_area
- content_objects
- content_graphics
- content_lines
- content_tables
- content_figures
- modm_data.pdf.page.Page
- index
- number
- label
- width
- height
- rotation
- bbox
- char_count
- char
- chars
- objlinks
- weblinks
- chars_in_area
- text_in_area
- structures
- find
- paths
- images
- graphic_clusters
- pypdfium2._helpers.page.PdfPage
- raw
- formenv
- parent
- get_width
- get_height
- get_size
- get_rotation
- set_rotation
- get_mediabox
- set_mediabox
- get_cropbox
- set_cropbox
- get_bleedbox
- set_bleedbox
- get_trimbox
- set_trimbox
- get_artbox
- set_artbox
- get_bbox
- get_textpage
- insert_obj
- remove_obj
- gen_content
- get_objects
- flatten
- render
- pypdfium2.internal.bases.AutoCloseable
- close