SPB Git

Repository Public

test_ocr_geometry.py 8.6 KB 201 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/unit/ocr/test_ocr_geometry.py8# Module           : Tests9# Repository       : https://git.spboucher.ai/spider10# Project Website  : Not specified11# Created          : 2026-12-0412# Last Modified    : 2026-12-0413#14# Author           : Simon-Pierre Boucher15# Position         : Professor of Finance16# Institution      : Université du Québec en Outaouais (UQO)17# Organization     : SP Boucher18# Website          : https://spboucher.ai19# Git              : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development      : dev@spboucher.ai23# Support          : support@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""OCR geometry: pure, run everywhere."""42from __future__ import annotations4344import pytest4546from spider.contracts import CaptureRef, OcrLine, Rect47from spider.ocr.geometry import contains, iou, merge_tile_lines, reading_order, to_css, touches_edge484950def capture(sha: str, css: tuple[float, float, float, float], dpr: float = 2.0, kind: str = "tile") -> CaptureRef:51    x, y, w, h = css52    return CaptureRef(kind=kind, path=f"/tmp/{sha}.png", sha256=sha, mime="image/png", width=round(w * dpr),53                      height=round(h * dpr), css=Rect(x=x, y=y, w=w, h=h), dpr=dpr)545556def line(text: str, x: float, y: float, w: float, h: float, confidence: float = 1.0) -> OcrLine:57    return OcrLine(text=text, confidence=confidence, x=x, y=y, w=w, h=h)585960def test_to_css_scales_by_dpr_and_offsets_by_capture_origin():61    cap = capture("a", (100, 1480, 640, 800), dpr=2)62    r = to_css(line("x", 40, 60, 200, 30), cap)63    assert (r.x, r.y, r.w, r.h) == (120, 1510, 100, 15)646566def test_to_css_dpr_one_and_fractional():67    assert to_css(line("x", 10, 20, 30, 40), capture("a", (0, 0, 800, 600), dpr=1)).model_dump() == \68        {"x": 10, "y": 20, "w": 30, "h": 40}69    r = to_css(Rect(x=30, y=45, w=60, h=15), capture("b", (5, 7, 800, 600), dpr=1.5))70    assert (r.x, r.y, r.w, r.h) == (25, 37, 40, 10)717273def test_to_css_rejects_bad_dpr():74    with pytest.raises(ValueError):75        to_css(line("x", 0, 0, 1, 1), capture("a", (0, 0, 10, 10), dpr=0))767778def test_iou_contains_touches():79    a, b = Rect(x=0, y=0, w=10, h=10), Rect(x=5, y=0, w=10, h=10)80    assert iou(a, a) == 1.081    assert iou(a, b) == pytest.approx(50 / 150)82    assert iou(a, Rect(x=20, y=20, w=5, h=5)) == 0.083    assert iou(a, Rect(x=10, y=0, w=5, h=5)) == 0.0  # touching edges do not overlap84    assert iou(Rect(x=0, y=0, w=0, h=0), Rect(x=0, y=0, w=0, h=0)) == 0.085    assert contains(a, Rect(x=2, y=2, w=6, h=6), margin=2)86    assert not contains(a, Rect(x=1, y=2, w=6, h=6), margin=2)87    assert touches_edge(Rect(x=0, y=3, w=4, h=4), a, 1)88    assert touches_edge(Rect(x=3, y=5, w=4, h=5), a, 1)89    assert not touches_edge(Rect(x=3, y=3, w=4, h=4), a, 1)909192def test_reading_order_rows_then_columns():93    rects = {94        "title": Rect(x=40, y=10, w=300, h=30),95        "left1": Rect(x=40, y=60, w=100, h=16),96        "right1": Rect(x=300, y=62, w=100, h=16),   # same row, 2 px lower97        "left2": Rect(x=40, y=90, w=100, h=16),98        "right2": Rect(x=300, y=88, w=100, h=16),   # same row, 2 px higher: must still come second99        "footer": Rect(x=40, y=140, w=100, h=10),100    }101    shuffled = ["right2", "footer", "left1", "title", "left2", "right1"]102    assert reading_order(shuffled, rect=lambda k: rects[k]) == ["title", "left1", "right1", "left2", "right2", "footer"]103104105def test_reading_order_is_deterministic_and_accepts_rects():106    rects = [Rect(x=10, y=0, w=5, h=10), Rect(x=10, y=0, w=5, h=10), Rect(x=0, y=0, w=5, h=10)]107    out = reading_order(rects)108    assert out[0] is rects[2] and out[1] is rects[0] and out[2] is rects[1]109    assert reading_order([]) == []110111112def two_tiles():113    """Two 400x300 CSS tiles at dpr 2, overlapping by 60 CSS px (y 240..300)."""114    return capture("tile-a", (0, 0, 400, 300)), capture("tile-b", (0, 240, 400, 300))115116117def test_merge_deduplicates_a_line_seen_in_both_tiles():118    a, b = two_tiles()119    pages = [120        (a, [line("Prix : 1 250,00 $", 40, 40, 300, 30), line("Livraison le 14 février", 40, 520, 360, 30, 0.9)]),121        # the same line read in tile b: css y = 240 + 40/2 = 260 = 520/2 in tile a122        (b, [line("Livraison le 14 fevrier", 41, 40, 360, 31, 1.0), line("Total : 2 847,35 $", 40, 400, 300, 30)]),123    ]124    merged = merge_tile_lines(pages)125    assert [m["text"] for m in merged] == ["Prix : 1 250,00 $", "Livraison le 14 fevrier", "Total : 2 847,35 $"]126    dup = merged[1]127    assert dup["capture_sha256"] == "tile-b" and dup["confidence"] == 1.0  # the more confident reading128    assert (dup["css"].x, dup["css"].y, dup["css"].w, dup["css"].h) == (20.5, 260, 180, 15.5)129    assert (dup["px"].x, dup["px"].y) == (41, 40)130    assert merged[2]["css"].y == 440131132133def test_merge_keeps_identical_text_at_different_positions():134    a, b = two_tiles()135    pages = [136        (a, [line("Voir le détail", 40, 100, 200, 30), line("Voir le détail", 40, 300, 200, 30)]),137        (b, [line("Voir le détail", 40, 300, 200, 30), line("Voir le détail", 420, 300, 200, 30)]),138    ]139    merged = merge_tile_lines(pages)140    assert [m["text"] for m in merged] == ["Voir le détail"] * 4141    assert sorted((m["css"].x, m["css"].y) for m in merged) == [(20, 50), (20, 150), (20, 390), (210, 390)]142143144def test_merge_keeps_different_text_at_the_same_position():145    a, b = two_tiles()146    pages = [(a, [line("12,99 $", 40, 520, 120, 30)]), (b, [line("Rupture de stock", 40, 40, 120, 30)])]147    assert len(merge_tile_lines(pages)) == 2148149150def test_merge_never_merges_two_lines_of_one_capture():151    a, _ = two_tiles()152    pages = [(a, [line("Total", 40, 40, 100, 30), line("Total", 41, 41, 100, 30, 0.5)])]153    assert len(merge_tile_lines(pages)) == 2154155156def test_merge_drops_a_line_cut_by_a_tile_edge_when_another_tile_shows_it_whole():157    a, b = two_tiles()158    pages = [159        # cut by the bottom edge of tile a (pixel 600 = css 300): only the top of the glyphs is visible160        (a, [line("Lnraicon Ie 1A tevner", 40, 582, 360, 18, 0.3)]),161        # complete in tile b: css y 291..306, well inside b (240..540)162        (b, [line("Livraison le 14 février", 40, 102, 360, 30, 1.0)]),163    ]164    merged = merge_tile_lines(pages)165    assert [m["text"] for m in merged] == ["Livraison le 14 février"]166167168def test_merge_keeps_an_edge_line_that_no_other_capture_covers():169    a, b = two_tiles()170    pages = [(a, [line("En-tête", 0, 0, 200, 30)]), (b, [line("Pied de page", 40, 570, 200, 30)])]171    assert [m["text"] for m in merge_tile_lines(pages)] == ["En-tête", "Pied de page"]172173174def test_merge_thresholds_are_configurable():175    a, b = two_tiles()176    # the copy in tile b is 2 CSS px lower: IoU = 13 / 17 = 0.76177    pages = [(a, [line("Livraison", 40, 520, 200, 30)]), (b, [line("Livraison", 40, 44, 200, 30)])]178    assert len(merge_tile_lines(pages)) == 1179    assert len(merge_tile_lines(pages, iou_threshold=0.9)) == 2180    near = [(a, [line("Livraison", 40, 520, 200, 30)]), (b, [line("Livraisons", 40, 44, 200, 30)])]181    assert len(merge_tile_lines(near)) == 1182    assert len(merge_tile_lines(near, text_threshold=1.0)) == 2183184185def test_merge_handles_side_by_side_tiles_and_mixed_dpr():186    left = capture("left", (0, 0, 300, 200), dpr=1)187    right = capture("right", (240, 0, 300, 200), dpr=3)188    pages = [189        (left, [line("Chambres : 3", 250, 50, 40, 16, 0.8)]),190        (right, [line("Chambres : 3", 30, 150, 120, 48, 0.9), line("Garage", 600, 150, 120, 48)]),191    ]192    merged = merge_tile_lines(pages)193    assert [m["text"] for m in merged] == ["Chambres : 3", "Garage"]194    assert merged[0]["capture_sha256"] == "right"195    assert (merged[1]["css"].x, merged[1]["css"].y, merged[1]["css"].w) == (440, 50, 40)196197198def test_merge_empty():199    assert merge_tile_lines([]) == []200    assert merge_tile_lines([(capture("a", (0, 0, 10, 10)), [])]) == []201
Files main
Menu

Theme