• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

bramp / build-along / 20158146015

12 Dec 2025 06:14AM UTC coverage: 90.787% (+0.3%) from 90.479%
20158146015

push

github

bramp
Ignore profile output.

12594 of 13872 relevant lines covered (90.79%)

0.91 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

99.11
/src/build_a_long/pdf_extract/classifier/classifier.py
1
"""
2
Rule-based classifier for labeling page elements.
3

4
Pipeline order and dependencies
5
--------------------------------
6
The classification pipeline operates in two main phases:
7

8
1. **Bottom-up Scoring**: All classifiers run independently to identify potential
9
   candidates (e.g. page numbers, part counts, step numbers) and score them based
10
   on heuristics. No construction of final elements happens here.
11

12
2. **Top-down Construction**: The root `PageClassifier` is invoked to construct
13
   the final `Page` object. It recursively requests the construction of its
14
   dependencies (e.g. "Give me the best PageNumber"), which in turn construct
15
   their own dependencies. This ensures a consistent and validated object tree.
16

17
"""
18

19
from __future__ import annotations
1✔
20

21
import logging
1✔
22

23
from build_a_long.pdf_extract.classifier.bags import (
1✔
24
    BagNumberClassifier,
25
    LoosePartSymbolClassifier,
26
    OpenBagClassifier,
27
)
28
from build_a_long.pdf_extract.classifier.batch_classification_result import (
1✔
29
    BatchClassificationResult,
30
)
31
from build_a_long.pdf_extract.classifier.block_filter import (
1✔
32
    filter_duplicate_blocks,
33
    filter_overlapping_text_blocks,
34
)
35
from build_a_long.pdf_extract.classifier.classification_result import (
1✔
36
    ClassificationResult,
37
)
38
from build_a_long.pdf_extract.classifier.classifier_config import ClassifierConfig
1✔
39
from build_a_long.pdf_extract.classifier.pages import (
1✔
40
    PageHintCollection,
41
)
42
from build_a_long.pdf_extract.classifier.pages.background_classifier import (
1✔
43
    BackgroundClassifier,
44
)
45
from build_a_long.pdf_extract.classifier.pages.divider_classifier import (
1✔
46
    DividerClassifier,
47
)
48
from build_a_long.pdf_extract.classifier.pages.page_classifier import PageClassifier
1✔
49
from build_a_long.pdf_extract.classifier.pages.page_number_classifier import (
1✔
50
    PageNumberClassifier,
51
)
52
from build_a_long.pdf_extract.classifier.pages.preview_classifier import (
1✔
53
    PreviewClassifier,
54
)
55
from build_a_long.pdf_extract.classifier.pages.progress_bar_classifier import (
1✔
56
    ProgressBarClassifier,
57
)
58
from build_a_long.pdf_extract.classifier.pages.progress_bar_indicator_classifier import (
1✔
59
    ProgressBarIndicatorClassifier,
60
)
61
from build_a_long.pdf_extract.classifier.pages.trivia_text_classifier import (
1✔
62
    TriviaTextClassifier,
63
)
64
from build_a_long.pdf_extract.classifier.parts import (
1✔
65
    PartCountClassifier,
66
    PartNumberClassifier,
67
    PartsClassifier,
68
    PartsImageClassifier,
69
    PartsListClassifier,
70
    PieceLengthClassifier,
71
    ScaleClassifier,
72
    ShineClassifier,
73
)
74
from build_a_long.pdf_extract.classifier.removal_reason import RemovalReason
1✔
75
from build_a_long.pdf_extract.classifier.steps import (
1✔
76
    ArrowClassifier,
77
    DiagramClassifier,
78
    RotationSymbolClassifier,
79
    StepClassifier,
80
    StepCountClassifier,
81
    StepNumberClassifier,
82
    SubAssemblyClassifier,
83
)
84
from build_a_long.pdf_extract.classifier.text import FontSizeHints, TextHistogram
1✔
85
from build_a_long.pdf_extract.classifier.topological_sort import topological_sort
1✔
86
from build_a_long.pdf_extract.extractor import PageData
1✔
87
from build_a_long.pdf_extract.extractor.bbox import filter_contained
1✔
88
from build_a_long.pdf_extract.extractor.lego_page_elements import (
1✔
89
    PageNumber,
90
    PartCount,
91
    PartsList,
92
    StepNumber,
93
)
94
from build_a_long.pdf_extract.extractor.page_blocks import Blocks
1✔
95

96
logger = logging.getLogger(__name__)
1✔
97

98
# Pages with more blocks than this threshold will be skipped during classification.
99
# This avoids O(n²) algorithms (like duplicate detection) that become prohibitively
100
# slow on pages with thousands of vector drawings. Such pages are typically info
101
# pages where each character is a separate vector graphic.
102
# TODO: Add spatial indexing to handle high-block pages efficiently.
103
MAX_BLOCKS_PER_PAGE = 1000
1✔
104

105

106
# TODO require config, so we don't accidentally use default empty config
107
def classify_elements(
1✔
108
    page: PageData, config: ClassifierConfig | None = None
109
) -> ClassificationResult:
110
    """Classify and label elements on a single page using rule-based heuristics.
111

112
    Args:
113
        page: A single PageData object to classify.
114
        config: Optional classifier configuration with font/page hints.
115
            If None, uses default empty configuration (no hints).
116
            For better classification accuracy, pass a config with
117
            FontSizeHints computed from multiple pages of the same PDF.
118

119
    Returns:
120
        A ClassificationResult object containing the classification results.
121
    """
122
    if config is None:
1✔
123
        config = ClassifierConfig()
1✔
124
    classifier = Classifier(config)
1✔
125

126
    return classifier.classify(page)
1✔
127

128

129
def classify_pages(
1✔
130
    pages: list[PageData], pages_for_hints: list[PageData] | None = None
131
) -> BatchClassificationResult:
132
    """Classify and label elements across multiple pages using rule-based heuristics.
133

134
    This function performs a three-phase process:
135
    1. Filtering phase: Mark duplicate/similar blocks as removed on each page
136
    2. Analysis phase: Build font size hints from text properties (excluding
137
       removed blocks)
138
    3. Classification phase: Use hints to guide element classification
139

140
    Args:
141
        pages: A list of PageData objects to classify.
142
        pages_for_hints: Optional list of pages to use for generating font/page hints.
143
            If None, uses `pages`. This allows generating hints from all pages
144
            while only classifying a subset (e.g., when using --pages filter).
145

146
    Returns:
147
        BatchClassificationResult containing per-page results and global histogram
148
    """
149

150
    # TODO There is a bunch of duplication in here between hints and non-hints. Refactor
151

152
    # Use all pages for hint generation if provided, otherwise use selected pages
153
    hint_pages = pages_for_hints if pages_for_hints is not None else pages
1✔
154

155
    # Phase 1: Filter duplicate blocks on each page and track removals
156
    # Skip pages with too many blocks to avoid O(n²) performance issues
157
    removed_blocks_per_page: list[dict[Blocks, RemovalReason]] = []
1✔
158
    skipped_pages: set[int] = set()  # Track page numbers that are skipped
1✔
159

160
    for page_data in pages:
1✔
161
        # Skip pages with too many blocks - these are likely info/inventory pages
162
        # with vectorized text that cause O(n²) algorithms to be very slow
163
        if len(page_data.blocks) > MAX_BLOCKS_PER_PAGE:
1✔
164
            logger.debug(
1✔
165
                f"Page {page_data.page_number}: skipping classification "
166
                f"({len(page_data.blocks)} blocks exceeds threshold of "
167
                f"{MAX_BLOCKS_PER_PAGE})"
168
            )
169
            skipped_pages.add(page_data.page_number)
1✔
170
            removed_blocks_per_page.append({})
1✔
171
            continue
1✔
172

173
        kept_blocks = page_data.blocks
1✔
174

175
        # Filter overlapping text blocks (e.g., "4" and "43" at same origin)
176
        kept_blocks, text_removed = filter_overlapping_text_blocks(kept_blocks)
1✔
177

178
        # Filter duplicate image/drawing blocks based on IOU
179
        kept_blocks, bbox_removed = filter_duplicate_blocks(kept_blocks)
1✔
180

181
        # Combine all removal mappings into a single dict for this page
182
        combined_removed_mapping = {
1✔
183
            **text_removed,
184
            **bbox_removed,
185
        }
186

187
        logger.debug(
1✔
188
            f"Page {page_data.page_number}: "
189
            f"filtered {len(text_removed)} overlapping text, "
190
            f"{len(bbox_removed)} duplicate bbox blocks"
191
        )
192

193
        removed_blocks_per_page.append(combined_removed_mapping)
1✔
194

195
    # Phase 2: Extract font size hints from hint pages (excluding removed blocks)
196
    # Build pages with non-removed blocks for hint extraction and histogram
197

198
    # Filter duplicates from hint pages (may be different from pages to classify)
199
    hint_pages_without_duplicates = []
1✔
200
    for page_data in hint_pages:
1✔
201
        # Skip high-block pages for hints too (same threshold)
202
        if len(page_data.blocks) > MAX_BLOCKS_PER_PAGE:
1✔
203
            continue
1✔
204

205
        # TODO We are re-filtering duplicates here; optimize by changing the API
206
        # to accept one list of PageData, and seperate by page_numbers.
207
        kept_blocks = page_data.blocks
1✔
208
        kept_blocks, _ = filter_overlapping_text_blocks(kept_blocks)
1✔
209
        kept_blocks, _ = filter_duplicate_blocks(kept_blocks)
1✔
210

211
        hint_pages_without_duplicates.append(
1✔
212
            PageData(
213
                page_number=page_data.page_number,
214
                bbox=page_data.bbox,
215
                blocks=kept_blocks,
216
            )
217
        )
218

219
    # Build pages without duplicates for classification
220
    pages_without_duplicates = []
1✔
221
    for page_data, removed_mapping in zip(pages, removed_blocks_per_page, strict=True):
1✔
222
        # We need to filter blocks that were removed by ANY filter
223
        non_removed_blocks = [
1✔
224
            block for block in page_data.blocks if block not in removed_mapping
225
        ]
226
        pages_without_duplicates.append(
1✔
227
            PageData(
228
                page_number=page_data.page_number,
229
                bbox=page_data.bbox,
230
                blocks=non_removed_blocks,
231
            )
232
        )
233

234
    # Generate hints from hint pages, histogram from pages to classify
235
    font_size_hints = FontSizeHints.from_pages(hint_pages_without_duplicates)
1✔
236
    page_hints = PageHintCollection.from_pages(hint_pages_without_duplicates)
1✔
237
    histogram = TextHistogram.from_pages(pages_without_duplicates)
1✔
238

239
    # Phase 3: Classify using the hints (on pages without duplicates)
240
    config = ClassifierConfig(font_size_hints=font_size_hints, page_hints=page_hints)
1✔
241
    classifier = Classifier(config)
1✔
242

243
    results = []
1✔
244
    for page_data, page_without_duplicates, removed_mapping in zip(
1✔
245
        pages, pages_without_duplicates, removed_blocks_per_page, strict=True
246
    ):
247
        # Handle skipped pages
248
        if page_data.page_number in skipped_pages:
1✔
249
            result = ClassificationResult(
1✔
250
                page_data=page_data,
251
                skipped_reason=(
252
                    f"Page has {len(page_data.blocks)} blocks, which exceeds "
253
                    f"the threshold of {MAX_BLOCKS_PER_PAGE}. This is likely an "
254
                    f"info/inventory page with vectorized text."
255
                ),
256
            )
257
            results.append(result)
1✔
258
            continue
1✔
259

260
        # Classify using only non-removed blocks
261
        result = classifier.classify(page_without_duplicates)
1✔
262

263
        # Update result to use original page_data (with all blocks)
264
        result.page_data = page_data
1✔
265

266
        # Mark removed blocks
267
        for removed_block, removal_reason in removed_mapping.items():
1✔
268
            result.mark_removed(removed_block, removal_reason)
1✔
269

270
        results.append(result)
1✔
271

272
    return BatchClassificationResult(results=results, histogram=histogram)
1✔
273

274

275
type Classifiers = (
1✔
276
    PageNumberClassifier
277
    | ProgressBarClassifier
278
    | ProgressBarIndicatorClassifier
279
    | PreviewClassifier
280
    | BackgroundClassifier
281
    | DividerClassifier
282
    | BagNumberClassifier
283
    | PartCountClassifier
284
    | PartNumberClassifier
285
    | StepNumberClassifier
286
    | StepCountClassifier
287
    | PieceLengthClassifier
288
    | ScaleClassifier
289
    | PartsClassifier
290
    | PartsListClassifier
291
    | PartsImageClassifier
292
    | ShineClassifier
293
    | OpenBagClassifier
294
    | LoosePartSymbolClassifier
295
    | DiagramClassifier
296
    | ArrowClassifier
297
    | SubAssemblyClassifier
298
    | StepClassifier
299
    | TriviaTextClassifier
300
    | PageClassifier
301
)
302

303

304
class Classifier:
1✔
305
    """
306
    Performs a single run of classification based on rules, configuration, and hints.
307
    This class should be stateless.
308
    """
309

310
    def __init__(self, config: ClassifierConfig):
1✔
311
        self.config = config
1✔
312
        # Sort classifiers topologically based on their dependencies
313
        self.classifiers = topological_sort(
1✔
314
            [
315
                PageNumberClassifier(config=config),
316
                ProgressBarIndicatorClassifier(config=config),
317
                ProgressBarClassifier(config=config),
318
                BackgroundClassifier(config=config),
319
                DividerClassifier(config=config),
320
                BagNumberClassifier(config=config),
321
                PartCountClassifier(config=config),
322
                PartNumberClassifier(config=config),
323
                StepNumberClassifier(config=config),
324
                StepCountClassifier(config=config),
325
                PieceLengthClassifier(config=config),
326
                ScaleClassifier(config=config),
327
                PartsClassifier(config=config),
328
                PartsListClassifier(config=config),
329
                DiagramClassifier(config=config),
330
                RotationSymbolClassifier(config=config),
331
                ArrowClassifier(config=config),
332
                PartsImageClassifier(config=config),
333
                ShineClassifier(config=config),
334
                OpenBagClassifier(config=config),
335
                LoosePartSymbolClassifier(config=config),
336
                PreviewClassifier(config=config),
337
                SubAssemblyClassifier(config=config),
338
                StepClassifier(config=config),
339
                TriviaTextClassifier(config=config),
340
                PageClassifier(config=config),
341
            ]
342
        )
343

344
    def classify(self, page_data: PageData) -> ClassificationResult:
1✔
345
        """
346
        Runs the classification logic and returns a result.
347
        It does NOT modify page_data directly.
348

349
        The classification process runs in three phases:
350
        1. Score all classifiers (bottom-up) - auto-registers classifiers
351
        2. Construct final elements (top-down starting from Page)
352
        """
353
        result = ClassificationResult(page_data=page_data)
1✔
354

355
        logger.debug(f"Starting classification for page {page_data.page_number}")
1✔
356

357
        # 1. Score all classifiers (Bottom-Up)
358
        # Note: score() automatically registers each classifier for its output labels
359
        for classifier in self.classifiers:
1✔
360
            classifier.score(result)
1✔
361

362
        # 2. Construct (Top-Down)
363
        # Find the PageClassifier to start the construction process
364
        page_classifier = next(
1✔
365
            c for c in self.classifiers if isinstance(c, PageClassifier)
366
        )
367
        page_classifier.build_all(result)
1✔
368

369
        # TODO Do we actualy ever add warnings?
370
        warnings = self._log_post_classification_warnings(page_data, result)
1✔
371
        for warning in warnings:
1✔
372
            result.add_warning(warning)
1✔
373

374
        return result
1✔
375

376
    def _log_post_classification_warnings(
1✔
377
        self, page_data: PageData, result: ClassificationResult
378
    ) -> list[str]:
379
        warnings = []
1✔
380

381
        # Check if there's a page number
382
        page_numbers = result.get_winners_by_score("page_number", PageNumber)
1✔
383
        if not page_numbers:
1✔
384
            warnings.append(f"Page {page_data.page_number}: missing page number")
1✔
385

386
        # Get elements by label
387
        parts_lists = result.get_winners_by_score("parts_list", PartsList)
1✔
388
        part_counts = result.get_winners_by_score("part_count", PartCount)
1✔
389

390
        for pl in parts_lists:
1✔
391
            inside_counts = filter_contained(part_counts, pl.bbox)
1✔
392
            if not inside_counts:
1✔
393
                warnings.append(
×
394
                    f"Page {page_data.page_number}: parts list at {pl.bbox} "
395
                    f"contains no part counts"
396
                )
397

398
        steps = result.get_winners_by_score("step_number", StepNumber)
1✔
399
        ABOVE_EPS = 2.0
1✔
400
        for step in steps:
1✔
401
            sb = step.bbox
1✔
402
            above = [pl for pl in parts_lists if pl.bbox.y1 <= sb.y0 + ABOVE_EPS]
1✔
403
            if not above:
1✔
404
                warnings.append(
1✔
405
                    f"Page {page_data.page_number}: step number '{step.value}' "
406
                    f"at {sb} has no parts list above it"
407
                )
408
        return warnings
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc