# -*- 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