|
| 1 | +"""Convert title / section document to processed entries.""" |
| 2 | + |
| 3 | +from dataclasses import dataclass |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +import pymupdf |
| 7 | +from pymupdf import Rect |
| 8 | +from swissgeol_doc_processing.text.textblock import TextBlock |
| 9 | + |
| 10 | +from src.entity.utils import _select_pages |
| 11 | +from src.models.feature_engineering import extract_and_cache_page_data |
| 12 | +from src.page_classes import PageClasses |
| 13 | +from src.page_structure import ProcessedEntities |
| 14 | +from src.utils.text_clustering import create_text_blocks |
| 15 | + |
| 16 | + |
| 17 | +@dataclass |
| 18 | +class TitleCandidateTextBlock: |
| 19 | + """Normalize text block size to document resolution.""" |
| 20 | + |
| 21 | + text: str |
| 22 | + n_lines: int |
| 23 | + rect: pymupdf.Rect |
| 24 | + |
| 25 | + def __init__(self, text_block: TextBlock, rect: Rect): |
| 26 | + """Create a scale invariant text block. |
| 27 | +
|
| 28 | + The normalized text block is contained in a fictive [0, 0, 1, 1] rect. |
| 29 | +
|
| 30 | + Args: |
| 31 | + text_block (TextBlock): Input text block. |
| 32 | + rect (Rect): Size of the page linked to text block. |
| 33 | + """ |
| 34 | + self.text = text_block.text |
| 35 | + self.line_count = text_block.line_count |
| 36 | + self.rect = pymupdf.Rect( |
| 37 | + text_block.rect.x0 / rect.width, |
| 38 | + text_block.rect.y0 / rect.height, |
| 39 | + text_block.rect.x1 / rect.width, |
| 40 | + text_block.rect.y1 / rect.height, |
| 41 | + ) |
| 42 | + |
| 43 | + @property |
| 44 | + def horizontal_centrality(self) -> float: |
| 45 | + """Horizontal centrality of the block. |
| 46 | +
|
| 47 | + Returns: |
| 48 | + float: Score in [0, 1] where 1 means the block is perfectly horizontally centered. |
| 49 | + """ |
| 50 | + return 1 - 2 * abs(0.5 - (self.rect.x1 + self.rect.x0) / 2) |
| 51 | + |
| 52 | + @property |
| 53 | + def font(self) -> float: |
| 54 | + """Normalized font size proxy. |
| 55 | +
|
| 56 | + Returns: |
| 57 | + float: Normalized line height in [0, 1] coordinate space. |
| 58 | + """ |
| 59 | + return self.rect.height / self.line_count |
| 60 | + |
| 61 | + @property |
| 62 | + def highness(self) -> float: |
| 63 | + """Vertical position score. |
| 64 | +
|
| 65 | + Higher values for blocks closer to the top of the page. |
| 66 | +
|
| 67 | + Returns: |
| 68 | + float: Score in [0, 1] where 1 means the block starts at the very top of the page. |
| 69 | + """ |
| 70 | + return 1 - self.rect.y0 |
| 71 | + |
| 72 | + @property |
| 73 | + def score(self) -> float: |
| 74 | + """Combined title-likelihood score. |
| 75 | +
|
| 76 | + The metric is based on horizontal centrality, font size, and vertical position |
| 77 | +
|
| 78 | + Returns: |
| 79 | + float: Estimated title-likelihood score. Higher means more likely a title. |
| 80 | + """ |
| 81 | + return self.horizontal_centrality * self.font * self.highness |
| 82 | + |
| 83 | + |
| 84 | +def _extract_title_from_page(page) -> str: |
| 85 | + """Extract the most likely title string from a single PDF page. |
| 86 | +
|
| 87 | + Builds text blocks from the page's text lines, wraps them as |
| 88 | + scale-invariant blocks, scores them by title-likelihood, and returns |
| 89 | + the text of the highest-scoring candidate. |
| 90 | +
|
| 91 | + Args: |
| 92 | + page (pymupdf.Page): The PDF page to analyse. |
| 93 | +
|
| 94 | + Returns: |
| 95 | + str: Detected title for the page. |
| 96 | + """ |
| 97 | + # Extract text block from page |
| 98 | + extraction_context = extract_and_cache_page_data(page) |
| 99 | + lines = extraction_context.text_lines |
| 100 | + text_blocks = create_text_blocks(lines) |
| 101 | + |
| 102 | + # Create list of text candidates and return best |
| 103 | + title_candidates = [TitleCandidateTextBlock(text_block=text_block, rect=page.rect) for text_block in text_blocks] |
| 104 | + title_candidates = sorted(title_candidates, key=lambda x: x.score, reverse=True) |
| 105 | + return title_candidates[0].text |
| 106 | + |
| 107 | + |
| 108 | +def document_to_titlepages( |
| 109 | + pdf_file: Path, classification: PageClasses, page_start: int, page_end: int, lang: str | None |
| 110 | +) -> list[ProcessedEntities]: |
| 111 | + """Extract title or section-header entities from a consecutive page range in a PDF. |
| 112 | +
|
| 113 | + Each page is processed individually and yields one ProcessedEntities entry whose `title` field |
| 114 | + contains detected title. |
| 115 | +
|
| 116 | + Args: |
| 117 | + pdf_file (Path): Path to the source PDF file. |
| 118 | + classification (PageClasses): Page class label to assign. |
| 119 | + page_start (int): First page index of the group (1-based). |
| 120 | + page_end (int): Last page index of the group (1-based). |
| 121 | + lang (str | None): Language code for the page group, or None if unknown. |
| 122 | +
|
| 123 | + Returns: |
| 124 | + list[ProcessedEntities]: One ProcessedEntities per page, each with its `title` |
| 125 | + field set to the highest-scoring title candidate extracted from that page. |
| 126 | + """ |
| 127 | + # Open the PDF file, select pages and save |
| 128 | + with pymupdf.Document(pdf_file) as doc: |
| 129 | + pdf_document_select = _select_pages(doc, page_start, page_end) |
| 130 | + |
| 131 | + return [ |
| 132 | + ProcessedEntities( |
| 133 | + classification=classification, |
| 134 | + page_start=page_start, |
| 135 | + page_end=page_end, |
| 136 | + language=lang, |
| 137 | + title=_extract_title_from_page(page=page), |
| 138 | + ) |
| 139 | + for page in pdf_document_select.pages() |
| 140 | + ] |
0 commit comments