Spaces:
Build error

File size: 7,860 Bytes
72464ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ea168e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72464ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ea168e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72464ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# -*- coding: utf-8 -*-
"""Heading detection from OCR bounding-box geometry.

Google Vision's DOCUMENT_TEXT_DETECTION returns a full layout hierarchy, but
only `fullTextAnnotation.text` was being kept. That discarded the one signal
identifying headings which carry no keyword and no number โ€” on the 2026-08-06
biology book, "ุงู„ุฏุนุงู…ู‡ ููŠ ุงู„ู†ุจุงุช" and "ุงู„ุฌู‡ุงุฒ ุงู„ู‡ูŠูƒู„ูŠ ููŠ ุงู„ุงู†ุณุงู†" are headings
purely because they are set in larger type on their own line. Without geometry
the book yielded 6 sections; a teacher scoping an exam needs ~30.
"""

from app.services.ocr_layout import (
    headings_from_vision_response,
    heading_lines,
    lines_from_vision_page,
)


def _word(text, top, height, left, width):
    return {
        "boundingBox": {"normalizedVertices": [
            {"x": left, "y": top}, {"x": left + width, "y": top},
            {"x": left + width, "y": top + height}, {"x": left, "y": top + height},
        ]},
        "symbols": [{"text": c} for c in text],
    }


def _line(words, top, height, left=0.1, word_width=0.08):
    """One visual line of Arabic, laid out the way Vision actually returns it.

    Arabic is RTL, so the FIRST word of the line sits at the largest x and each
    following word is further left. These fixtures previously placed word 0 at
    the smallest x โ€” Latin geometry โ€” which made a left-to-right join look
    correct and hid the fact that every real heading came back with its words
    reversed ("ุงู„ุฃูˆู„ู‰ ุงู„ูˆุญุฏุฉ" for "ุงู„ูˆุญุฏุฉ ุงู„ุฃูˆู„ู‰"). Confirmed against live
    DOCUMENT_TEXT_DETECTION output on 2026-08-07.
    """
    n = len(words)
    return {"words": [
        _word(w, top, height, left + (n - 1 - i) * word_width, word_width)
        for i, w in enumerate(words)
    ]}


def _ltr_line(words, top, height, left=0.1, word_width=0.08):
    """A Latin line โ€” word 0 leftmost, order preserved on join."""
    return {"words": [
        _word(w, top, height, left + i * word_width, word_width)
        for i, w in enumerate(words)
    ]}


def _page(paragraphs):
    return {"blocks": [{"paragraphs": paragraphs}]}


BODY = [
    _line(["ูŠู„ุฌุง", "ุงู„ู†ุจุงุช", "ุงู„ูŠ", "ูˆุณุงุฆู„", "ูƒุซูŠุฑู‡", "ู„ุฏุนู…ู‡", "ู…ู†ู‡ุง"], 0.20, 0.022, 0.05, 0.10),
    _line(["ุจุนุถ", "ุงู„ู…ูˆุงุฏ", "ููŠ", "ุฌุฏุฑ", "ุฎู„ุงูŠุงู‡", "ูู„ูƒูŠ", "ุชุญุงูุธ"], 0.26, 0.022, 0.05, 0.10),
    _line(["ุงู„ุฎุงุฑุฌูŠู‡", "ุนู„ูŠ", "ุงู†ุณุฌู‡", "ุงู„ู†ุจุงุช", "ุงู„ุฏุงุฎู„ูŠู‡", "ูˆุชุญูˆู„"], 0.32, 0.022, 0.05, 0.10),
]


def test_larger_type_on_its_own_line_is_a_heading():
    """The case keyword and decimal detectors are structurally blind to."""
    page = _page([_line(["ุงู„ุฏุนุงู…ู‡", "ููŠ", "ุงู„ู†ุจุงุช"], 0.10, 0.040)] + BODY)

    found = heading_lines(lines_from_vision_page(page))

    assert [f.text for f in found] == ["ุงู„ุฏุนุงู…ู‡ ููŠ ุงู„ู†ุจุงุช"]


def test_body_text_is_not_a_heading():
    page = _page(BODY)
    assert heading_lines(lines_from_vision_page(page)) == []


def test_figure_captions_are_rejected():
    """Captions are short and set apart, but they are not sections."""
    page = _page([_line(["ุดูƒู„", "(1)", "ุงู„ุนู…ูˆุฏ"], 0.10, 0.040)] + BODY)

    assert heading_lines(lines_from_vision_page(page)) == []


def test_page_furniture_is_rejected():
    page = _page([_line(["ุนู„ู…", "ุงู„ุงุญูŠุงุก", "ู„ู„ุซุงู†ูˆูŠู‡"], 0.10, 0.040)] + BODY)

    assert heading_lines(lines_from_vision_page(page)) == []


def test_multiple_headings_come_back_in_reading_order():
    page = _page([
        _line(["ุงู„ุฏุนุงู…ู‡", "ููŠ", "ุงู„ู†ุจุงุช"], 0.10, 0.040),
        *BODY,
        _line(["ุงู„ุฌู‡ุงุฒ", "ุงู„ู‡ูŠูƒู„ูŠ", "ููŠ", "ุงู„ุงู†ุณุงู†"], 0.55, 0.041),
    ])

    found = heading_lines(lines_from_vision_page(page))

    assert [f.text for f in found] == [
        "ุงู„ุฏุนุงู…ู‡ ููŠ ุงู„ู†ุจุงุช", "ุงู„ุฌู‡ุงุฒ ุงู„ู‡ูŠูƒู„ูŠ ููŠ ุงู„ุงู†ุณุงู†",
    ]


def test_arabic_words_are_joined_right_to_left():
    """The defect that made this whole source unusable.

    Words are sorted by ascending x for line grouping, which is reading order
    for Latin and exactly backwards for Arabic. Joining in that order produced
    reversed titles that matched no keyword pattern and read as nonsense to the
    LLM verifier โ€” which is why `accepted_by.ocr_layout` was 0 on every book.
    """
    page = _page([_line(["ุงู„ูˆุญุฏุฉ", "ุงู„ุฃูˆู„ู‰"], 0.10, 0.040)] + BODY)

    assert [ln.text for ln in heading_lines(lines_from_vision_page(page))] == [
        "ุงู„ูˆุญุฏุฉ ุงู„ุฃูˆู„ู‰",
    ]


def test_latin_lines_keep_left_to_right_order():
    """Only Arabic-majority lines reverse โ€” technical terms must not."""
    page = _page([_ltr_line(["Chromosomal", "Mutations"], 0.10, 0.040)] + BODY)

    assert [ln.text for ln in heading_lines(lines_from_vision_page(page))] == [
        "Chromosomal Mutations",
    ]


def test_prose_the_height_test_cannot_reject_is_rejected_by_length():
    """Arabic diacritics defeat the font-size proxy.

    Tashkeel extends a word's bounding box above and below the letters, so
    vocalized body text measures as tall as a real heading. On the 2026-08-07
    Arabic book this let a 75-character run of prose through. Length is what
    still separates a label from a paragraph.
    """
    vocalized = _line(
        ["ุฃูŽูƒูŽู„ูŽ", "ุฃูŽูƒู’ู„ุง", "ุฃุญุณู†", "ุฅุญุณุงู†ู‹ุง", "ุฅู„ู‰", "ุฃูุฎุช", "ุฃุฎ", "ู…ุซู„", "ุงู„ู…ูˆุงุถุน", "ู…ู†"],
        0.10, 0.040,
    )
    page = _page([vocalized] + BODY)

    assert heading_lines(lines_from_vision_page(page)) == []


def test_a_page_with_too_little_text_yields_nothing():
    """No baseline can be established, so nothing may be called 'larger'."""
    page = _page([_line(["ุนู†ูˆุงู†", "ู‚ุตูŠุฑ"], 0.10, 0.05)])

    assert heading_lines(lines_from_vision_page(page)) == []


def test_uniform_type_yields_no_headings():
    """Everything the same size means nothing stands out."""
    page = _page([_line(["ุณุทุฑ", "ุฑู‚ู…", str(i), "ู†ุต", "ุนุงุฏูŠ"], 0.1 + i * 0.06, 0.022)
                  for i in range(6)])

    assert heading_lines(lines_from_vision_page(page)) == []


def test_malformed_response_does_not_raise():
    """OCR must never be broken by unexpected layout payloads."""
    assert headings_from_vision_response({}) == []
    assert headings_from_vision_response({"fullTextAnnotation": {}}) == []
    assert headings_from_vision_response({"fullTextAnnotation": {"pages": [{}]}}) == []


# โ”€โ”€ Integration with the candidate pool โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def test_layout_candidates_reach_the_heading_pool():
    from app.services.heading_detector import (
        _ACCEPT_THRESHOLD, _LLM_REVIEW_LOW, _candidates_from_ocr_layout,
    )

    layout = {12: ["ุงู„ุฏุนุงู…ู‡ ููŠ ุงู„ู†ุจุงุช"], 40: ["ุงู„ุฌู‡ุงุฒ ุงู„ู‡ูŠูƒู„ูŠ ููŠ ุงู„ุงู†ุณุงู†"]}
    cands = _candidates_from_ocr_layout(layout, {12, 40})

    assert [c.page_num for c in cands] == [12, 40]
    # Geometry alone cannot confirm the level or corroborate an ordinal, so
    # these must land in the LLM-review band rather than auto-accept.
    assert all(_LLM_REVIEW_LOW <= c.confidence < _ACCEPT_THRESHOLD for c in cands)


def test_layout_candidates_respect_page_eligibility():
    from app.services.heading_detector import _candidates_from_ocr_layout

    assert _candidates_from_ocr_layout({99: ["ุนู†ูˆุงู† ู…ุง"]}, set()) == []


def test_layout_titles_are_trimmed_like_any_other():
    from app.services.heading_detector import _candidates_from_ocr_layout

    long_title = "ุงู„ูุตู„ ุงู„ุงูˆู„ ุงู„ุฏุนุงู…ู‡ ููŠ ู†ู‡ุงูŠู‡ ู‡ุฐุง ุงู„ูุตู„ ูŠู†ุจุบูŠ ุงู† ูŠูƒูˆู† ุงู„ุทุงู„ุจ"
    cands = _candidates_from_ocr_layout({5: [long_title]}, {5})

    assert "ูŠู†ุจุบูŠ" not in cands[0].text