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

bramp / build-along / 20149797779

11 Dec 2025 10:42PM UTC coverage: 90.123% (+0.4%) from 89.769%
20149797779

push

github

bramp
refactor(classifier): Split rules.py into modular sub-files

Splits src/build_a_long/pdf_extract/classifier/rules.py into a modular package src/build_a_long/pdf_extract/classifier/rules/ with base.py, text.py, geometry.py, and visual.py. This improves maintainability and organization of the growing ruleset. All existing rules are re-exported from rules/__init__.py to maintain backward compatibility for imports.

217 of 243 new or added lines in 5 files covered. (89.3%)

64 existing lines in 8 files now uncovered.

12045 of 13365 relevant lines covered (90.12%)

0.9 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
    ShineClassifier,
72
)
73
from build_a_long.pdf_extract.classifier.removal_reason import RemovalReason
1✔
74
from build_a_long.pdf_extract.classifier.steps import (
1✔
75
    ArrowClassifier,
76
    DiagramClassifier,
77
    RotationSymbolClassifier,
78
    StepClassifier,
79
    StepCountClassifier,
80
    StepNumberClassifier,
81
    SubAssemblyClassifier,
82
)
83
from build_a_long.pdf_extract.classifier.text import FontSizeHints, TextHistogram
1✔
84
from build_a_long.pdf_extract.classifier.topological_sort import topological_sort
1✔
85
from build_a_long.pdf_extract.extractor import PageData
1✔
86
from build_a_long.pdf_extract.extractor.bbox import filter_contained
1✔
87
from build_a_long.pdf_extract.extractor.lego_page_elements import (
1✔
88
    PageNumber,
89
    PartCount,
90
    PartsList,
91
    StepNumber,
92
)
93
from build_a_long.pdf_extract.extractor.page_blocks import Blocks
1✔
94

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

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

104

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

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

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

125
    return classifier.classify(page)
1✔
126

127

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

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

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

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

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

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

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

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

172
        kept_blocks = page_data.blocks
1✔
173

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

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

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

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

192
        removed_blocks_per_page.append(combined_removed_mapping)
1✔
193

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

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

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

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

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

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

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

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

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

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

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

269
        results.append(result)
1✔
270

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

273

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

301

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

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

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

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

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

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

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

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

371
        return result
1✔
372

373
    def _log_post_classification_warnings(
1✔
374
        self, page_data: PageData, result: ClassificationResult
375
    ) -> list[str]:
376
        warnings = []
1✔
377

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

383
        # Get elements by label
384
        parts_lists = result.get_winners_by_score("parts_list", PartsList)
1✔
385
        part_counts = result.get_winners_by_score("part_count", PartCount)
1✔
386

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

395
        steps = result.get_winners_by_score("step_number", StepNumber)
1✔
396
        ABOVE_EPS = 2.0
1✔
397
        for step in steps:
1✔
398
            sb = step.bbox
1✔
399
            above = [pl for pl in parts_lists if pl.bbox.y1 <= sb.y0 + ABOVE_EPS]
1✔
400
            if not above:
1✔
401
                warnings.append(
1✔
402
                    f"Page {page_data.page_number}: step number '{step.value}' "
403
                    f"at {sb} has no parts list above it"
404
                )
405
        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