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

bramp / build-along / 20015271182

08 Dec 2025 03:02AM UTC coverage: 90.402% (+0.1%) from 90.299%
20015271182

push

github

bramp
Minor rename of property in subassembly config.

3 of 3 new or added lines in 1 file covered. (100.0%)

125 existing lines in 14 files now uncovered.

11039 of 12211 relevant lines covered (90.4%)

0.9 hits per line

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

99.08
/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
    NewBagClassifier,
26
)
27
from build_a_long.pdf_extract.classifier.batch_classification_result import (
1✔
28
    BatchClassificationResult,
29
)
30
from build_a_long.pdf_extract.classifier.block_filter import (
1✔
31
    filter_duplicate_blocks,
32
    filter_overlapping_text_blocks,
33
)
34
from build_a_long.pdf_extract.classifier.classification_result import (
1✔
35
    ClassificationResult,
36
)
37
from build_a_long.pdf_extract.classifier.classifier_config import ClassifierConfig
1✔
38
from build_a_long.pdf_extract.classifier.pages import (
1✔
39
    PageHintCollection,
40
)
41
from build_a_long.pdf_extract.classifier.pages.background_classifier import (
1✔
42
    BackgroundClassifier,
43
)
44
from build_a_long.pdf_extract.classifier.pages.divider_classifier import (
1✔
45
    DividerClassifier,
46
)
47
from build_a_long.pdf_extract.classifier.pages.page_classifier import PageClassifier
1✔
48
from build_a_long.pdf_extract.classifier.pages.page_number_classifier import (
1✔
49
    PageNumberClassifier,
50
)
51
from build_a_long.pdf_extract.classifier.pages.progress_bar_classifier import (
1✔
52
    ProgressBarClassifier,
53
)
54
from build_a_long.pdf_extract.classifier.parts import (
1✔
55
    PartCountClassifier,
56
    PartNumberClassifier,
57
    PartsClassifier,
58
    PartsImageClassifier,
59
    PartsListClassifier,
60
    PieceLengthClassifier,
61
    ShineClassifier,
62
)
63
from build_a_long.pdf_extract.classifier.removal_reason import RemovalReason
1✔
64
from build_a_long.pdf_extract.classifier.steps import (
1✔
65
    ArrowClassifier,
66
    DiagramClassifier,
67
    RotationSymbolClassifier,
68
    StepClassifier,
69
    StepCountClassifier,
70
    StepNumberClassifier,
71
    SubAssemblyClassifier,
72
)
73
from build_a_long.pdf_extract.classifier.text import FontSizeHints, TextHistogram
1✔
74
from build_a_long.pdf_extract.classifier.topological_sort import topological_sort
1✔
75
from build_a_long.pdf_extract.extractor import PageData
1✔
76
from build_a_long.pdf_extract.extractor.bbox import filter_contained
1✔
77
from build_a_long.pdf_extract.extractor.lego_page_elements import (
1✔
78
    PageNumber,
79
    PartCount,
80
    PartsList,
81
    StepNumber,
82
)
83
from build_a_long.pdf_extract.extractor.page_blocks import Blocks
1✔
84

85
logger = logging.getLogger(__name__)
1✔
86

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

94

95
# TODO require config, so we don't accidentally use default empty config
96
def classify_elements(
1✔
97
    page: PageData, config: ClassifierConfig | None = None
98
) -> ClassificationResult:
99
    """Classify and label elements on a single page using rule-based heuristics.
100

101
    Args:
102
        page: A single PageData object to classify.
103
        config: Optional classifier configuration with font/page hints.
104
            If None, uses default empty configuration (no hints).
105
            For better classification accuracy, pass a config with
106
            FontSizeHints computed from multiple pages of the same PDF.
107

108
    Returns:
109
        A ClassificationResult object containing the classification results.
110
    """
111
    if config is None:
1✔
112
        config = ClassifierConfig()
1✔
113
    classifier = Classifier(config)
1✔
114

115
    return classifier.classify(page)
1✔
116

117

118
def classify_pages(
1✔
119
    pages: list[PageData], pages_for_hints: list[PageData] | None = None
120
) -> BatchClassificationResult:
121
    """Classify and label elements across multiple pages using rule-based heuristics.
122

123
    This function performs a three-phase process:
124
    1. Filtering phase: Mark duplicate/similar blocks as removed on each page
125
    2. Analysis phase: Build font size hints from text properties (excluding
126
       removed blocks)
127
    3. Classification phase: Use hints to guide element classification
128

129
    Args:
130
        pages: A list of PageData objects to classify.
131
        pages_for_hints: Optional list of pages to use for generating font/page hints.
132
            If None, uses `pages`. This allows generating hints from all pages
133
            while only classifying a subset (e.g., when using --pages filter).
134

135
    Returns:
136
        BatchClassificationResult containing per-page results and global histogram
137
    """
138

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

141
    # Use all pages for hint generation if provided, otherwise use selected pages
142
    hint_pages = pages_for_hints if pages_for_hints is not None else pages
1✔
143

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

149
    for page_data in pages:
1✔
150
        # Skip pages with too many blocks - these are likely info/inventory pages
151
        # with vectorized text that cause O(n²) algorithms to be very slow
152
        if len(page_data.blocks) > MAX_BLOCKS_PER_PAGE:
1✔
153
            logger.debug(
1✔
154
                f"Page {page_data.page_number}: skipping classification "
155
                f"({len(page_data.blocks)} blocks exceeds threshold of "
156
                f"{MAX_BLOCKS_PER_PAGE})"
157
            )
158
            skipped_pages.add(page_data.page_number)
1✔
159
            removed_blocks_per_page.append({})
1✔
160
            continue
1✔
161

162
        kept_blocks = page_data.blocks
1✔
163

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

167
        # Filter duplicate image/drawing blocks based on IOU
168
        kept_blocks, bbox_removed = filter_duplicate_blocks(kept_blocks)
1✔
169

170
        # Combine all removal mappings into a single dict for this page
171
        combined_removed_mapping = {
1✔
172
            **text_removed,
173
            **bbox_removed,
174
        }
175

176
        logger.debug(
1✔
177
            f"Page {page_data.page_number}: "
178
            f"filtered {len(text_removed)} overlapping text, "
179
            f"{len(bbox_removed)} duplicate bbox blocks"
180
        )
181

182
        removed_blocks_per_page.append(combined_removed_mapping)
1✔
183

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

187
    # Filter duplicates from hint pages (may be different from pages to classify)
188
    hint_pages_without_duplicates = []
1✔
189
    for page_data in hint_pages:
1✔
190
        # Skip high-block pages for hints too (same threshold)
191
        if len(page_data.blocks) > MAX_BLOCKS_PER_PAGE:
1✔
192
            continue
1✔
193

194
        # TODO We are re-filtering duplicates here; optimize by changing the API
195
        # to accept one list of PageData, and seperate by page_numbers.
196
        kept_blocks = page_data.blocks
1✔
197
        kept_blocks, _ = filter_overlapping_text_blocks(kept_blocks)
1✔
198
        kept_blocks, _ = filter_duplicate_blocks(kept_blocks)
1✔
199

200
        hint_pages_without_duplicates.append(
1✔
201
            PageData(
202
                page_number=page_data.page_number,
203
                bbox=page_data.bbox,
204
                blocks=kept_blocks,
205
            )
206
        )
207

208
    # Build pages without duplicates for classification
209
    pages_without_duplicates = []
1✔
210
    for page_data, removed_mapping in zip(pages, removed_blocks_per_page, strict=True):
1✔
211
        # We need to filter blocks that were removed by ANY filter
212
        non_removed_blocks = [
1✔
213
            block for block in page_data.blocks if block not in removed_mapping
214
        ]
215
        pages_without_duplicates.append(
1✔
216
            PageData(
217
                page_number=page_data.page_number,
218
                bbox=page_data.bbox,
219
                blocks=non_removed_blocks,
220
            )
221
        )
222

223
    # Generate hints from hint pages, histogram from pages to classify
224
    font_size_hints = FontSizeHints.from_pages(hint_pages_without_duplicates)
1✔
225
    page_hints = PageHintCollection.from_pages(hint_pages_without_duplicates)
1✔
226
    histogram = TextHistogram.from_pages(pages_without_duplicates)
1✔
227

228
    # Phase 3: Classify using the hints (on pages without duplicates)
229
    config = ClassifierConfig(font_size_hints=font_size_hints, page_hints=page_hints)
1✔
230
    classifier = Classifier(config)
1✔
231

232
    results = []
1✔
233
    for page_data, page_without_duplicates, removed_mapping in zip(
1✔
234
        pages, pages_without_duplicates, removed_blocks_per_page, strict=True
235
    ):
236
        # Handle skipped pages
237
        if page_data.page_number in skipped_pages:
1✔
238
            result = ClassificationResult(
1✔
239
                page_data=page_data,
240
                skipped_reason=(
241
                    f"Page has {len(page_data.blocks)} blocks, which exceeds "
242
                    f"the threshold of {MAX_BLOCKS_PER_PAGE}. This is likely an "
243
                    f"info/inventory page with vectorized text."
244
                ),
245
            )
246
            results.append(result)
1✔
247
            continue
1✔
248

249
        # Classify using only non-removed blocks
250
        result = classifier.classify(page_without_duplicates)
1✔
251

252
        # Update result to use original page_data (with all blocks)
253
        result.page_data = page_data
1✔
254

255
        # Mark removed blocks
256
        for removed_block, removal_reason in removed_mapping.items():
1✔
257
            result.mark_removed(removed_block, removal_reason)
1✔
258

259
        results.append(result)
1✔
260

261
    return BatchClassificationResult(results=results, histogram=histogram)
1✔
262

263

264
type Classifiers = (
1✔
265
    PageNumberClassifier
266
    | ProgressBarClassifier
267
    | BackgroundClassifier
268
    | DividerClassifier
269
    | BagNumberClassifier
270
    | PartCountClassifier
271
    | PartNumberClassifier
272
    | StepNumberClassifier
273
    | StepCountClassifier
274
    | PieceLengthClassifier
275
    | PartsClassifier
276
    | PartsListClassifier
277
    | PartsImageClassifier
278
    | ShineClassifier
279
    | NewBagClassifier
280
    | DiagramClassifier
281
    | ArrowClassifier
282
    | SubAssemblyClassifier
283
    | StepClassifier
284
    | PageClassifier
285
)
286

287

288
class Classifier:
1✔
289
    """
290
    Performs a single run of classification based on rules, configuration, and hints.
291
    This class should be stateless.
292
    """
293

294
    def __init__(self, config: ClassifierConfig):
1✔
295
        self.config = config
1✔
296
        # Sort classifiers topologically based on their dependencies
297
        self.classifiers = topological_sort(
1✔
298
            [
299
                PageNumberClassifier(config=config),
300
                ProgressBarClassifier(config=config),
301
                BackgroundClassifier(config=config),
302
                DividerClassifier(config=config),
303
                BagNumberClassifier(config=config),
304
                PartCountClassifier(config=config),
305
                PartNumberClassifier(config=config),
306
                StepNumberClassifier(config=config),
307
                StepCountClassifier(config=config),
308
                PieceLengthClassifier(config=config),
309
                PartsClassifier(config=config),
310
                PartsListClassifier(config=config),
311
                DiagramClassifier(config=config),
312
                RotationSymbolClassifier(config=config),
313
                ArrowClassifier(config=config),
314
                PartsImageClassifier(config=config),
315
                ShineClassifier(config=config),
316
                NewBagClassifier(config=config),
317
                SubAssemblyClassifier(config=config),
318
                StepClassifier(config=config),
319
                PageClassifier(config=config),
320
            ]
321
        )
322

323
    def classify(self, page_data: PageData) -> ClassificationResult:
1✔
324
        """
325
        Runs the classification logic and returns a result.
326
        It does NOT modify page_data directly.
327

328
        The classification process runs in three phases:
329
        1. Score all classifiers (bottom-up) - auto-registers classifiers
330
        2. Construct final elements (top-down starting from Page)
331
        """
332
        result = ClassificationResult(page_data=page_data)
1✔
333

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

336
        # 1. Score all classifiers (Bottom-Up)
337
        # Note: score() automatically registers each classifier for its output labels
338
        for classifier in self.classifiers:
1✔
339
            classifier.score(result)
1✔
340

341
        # 2. Construct (Top-Down)
342
        # Find the PageClassifier to start the construction process
343
        page_classifier = next(
1✔
344
            c for c in self.classifiers if isinstance(c, PageClassifier)
345
        )
346
        page_classifier.build_all(result)
1✔
347

348
        # TODO Do we actualy ever add warnings?
349
        warnings = self._log_post_classification_warnings(page_data, result)
1✔
350
        for warning in warnings:
1✔
351
            result.add_warning(warning)
1✔
352

353
        return result
1✔
354

355
    def _log_post_classification_warnings(
1✔
356
        self, page_data: PageData, result: ClassificationResult
357
    ) -> list[str]:
358
        warnings = []
1✔
359

360
        # Check if there's a page number
361
        page_numbers = result.get_winners_by_score("page_number", PageNumber)
1✔
362
        if not page_numbers:
1✔
363
            warnings.append(f"Page {page_data.page_number}: missing page number")
1✔
364

365
        # Get elements by label
366
        parts_lists = result.get_winners_by_score("parts_list", PartsList)
1✔
367
        part_counts = result.get_winners_by_score("part_count", PartCount)
1✔
368

369
        for pl in parts_lists:
1✔
370
            inside_counts = filter_contained(part_counts, pl.bbox)
1✔
371
            if not inside_counts:
1✔
UNCOV
372
                warnings.append(
×
373
                    f"Page {page_data.page_number}: parts list at {pl.bbox} "
374
                    f"contains no part counts"
375
                )
376

377
        steps = result.get_winners_by_score("step_number", StepNumber)
1✔
378
        ABOVE_EPS = 2.0
1✔
379
        for step in steps:
1✔
380
            sb = step.bbox
1✔
381
            above = [pl for pl in parts_lists if pl.bbox.y1 <= sb.y0 + ABOVE_EPS]
1✔
382
            if not above:
1✔
383
                warnings.append(
1✔
384
                    f"Page {page_data.page_number}: step number '{step.value}' "
385
                    f"at {sb} has no parts list above it"
386
                )
387
        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