Download tests/reader/backend/test_reader_ocr_validation.py from VoiceOfML/Search: direct link, hf CLI and curl.
- Browser
- Download file 40.4 kB
-
https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/tests/reader/backend/test_reader_ocr_validation.py
- Command line
-
hf download hf://spaces/VoiceOfML/Search/tests/reader/backend/test_reader_ocr_validation.py
-
curl -L -o test_reader_ocr_validation.py https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/tests/reader/backend/test_reader_ocr_validation.py
40.4 kB
| """Validation and search contracts for the bounded PDF text index.""" | |
| import asyncio | |
| import gzip | |
| import json | |
| import random | |
| import time | |
| import unittest | |
| from collections import OrderedDict | |
| from types import SimpleNamespace | |
| from unittest.mock import AsyncMock, patch | |
| from fastapi.responses import JSONResponse | |
| from backend import app | |
| from backend import reader_ocr | |
| def book(pages): | |
| return {"version": 2, "kind": "pdf-book-text", "complete": True, | |
| "offset_unit": "unicode-codepoint", "source_sha256": "a" * 64, | |
| "page_count": len(pages), "pages": pages} | |
| def page(number=1, text="Hello", spans=None): | |
| return {"page": number, "text": text, "layout": {"offset_unit": "unicode-codepoint"}, | |
| "text_spans": [] if spans is None else spans} | |
| def encode(payload): | |
| return gzip.compress(json.dumps(payload, ensure_ascii=False).encode()) | |
| class ReaderOcrValidationTests(unittest.TestCase): | |
| def test_count_after_selected_page_preserves_original_offsets_and_boxes(self): | |
| spans = [{"start": 0, "end": 2, "box": [0, 0, .5, 1]}, | |
| {"start": 2, "end": 3, "box": [.5, 0, 1, 1]}] | |
| pages, _ = app.parse_reader_ocr_book(encode(book([ | |
| page(1, "ßßx", spans), page(2, "aßßb", [ | |
| {"start": 0, "end": 4, "box": [0, 0, 1, 1]}]), page(3, "ß") | |
| ]))) | |
| total, hits = app.search_reader_ocr_pages(pages, "s", 1, 3) | |
| self.assertEqual(total, 10) | |
| self.assertEqual([(hit["page"], hit["start"], hit["length"]) for hit in hits], | |
| [(1, 0, 1), (1, 0, 1), (1, 1, 1)]) | |
| self.assertEqual([hit["boxes"] for hit in hits], [[[0, 0, .5, 1]]] * 3) | |
| total, hits = app.search_reader_ocr_pages(pages, "s", 2, 3) | |
| self.assertEqual(total, 10) | |
| self.assertEqual([(hit["page"], hit["start"], hit["length"]) for hit in hits], | |
| [(1, 1, 1), (2, 1, 1), (2, 1, 1)]) | |
| self.assertEqual(app.search_reader_ocr_pages(pages, "s", 99, 3), (10, [])) | |
| def test_count_fast_path_matches_independent_per_match_reference(self): | |
| def reference(pages, needle, page_no, page_size): | |
| start_index = (page_no - 1) * page_size | |
| end_index = start_index + page_size | |
| hits = [] | |
| all_hits = [] | |
| if not needle: | |
| return 0, [] | |
| for item in pages: | |
| text = item["text"] | |
| folded, mapping = reader_ocr.fold_reader_ocr_text(text) | |
| position = 0 | |
| while True: | |
| found = folded.find(needle, position) | |
| if found < 0: | |
| break | |
| if mapping is None: | |
| start, end = found, found + len(needle) | |
| else: | |
| start, end = mapping[found], mapping[found + len(needle) - 1] + 1 | |
| lo, hi = max(0, start - 72), min(len(text), end + 88) | |
| all_hits.append({"page": item["page"], "start": start, "length": end - start, | |
| "snippet": text[lo:hi], "snippet_start": start - lo, | |
| "boxes": [span["box"] for span in item["spans"] | |
| if span["end"] > start and span["start"] < end]}) | |
| position = found + len(needle) | |
| for index, hit in enumerate(all_hits): | |
| if start_index <= index < end_index: | |
| hits.append(hit) | |
| return len(all_hits), hits | |
| rng = random.Random(20261104) | |
| alphabet = ["a", "A", "中", "ß", "İ", "fi", "😀", " ", "\n"] | |
| for _ in range(400): | |
| pages = [] | |
| for number in range(1, rng.randrange(1, 6)): | |
| text = "".join(rng.choices(alphabet, k=rng.randrange(70))) | |
| folded, mapping = reader_ocr.fold_reader_ocr_text(text) | |
| item = {"page": number, "text": text, "folded": folded, "spans": [], "layout": {}} | |
| if text: | |
| item["spans"] = [{"start": 0, "end": len(text), "box": [0, 0, 1, 1]}] | |
| if rng.randrange(2): | |
| item["fold_map"] = mapping | |
| pages.append(item) | |
| needle = rng.choice(["", "a", "中", "s", "ss", "i\u0307", "fi", "😀", "missing"]) | |
| page_no, page_size = rng.randrange(-2, 8), rng.randrange(-1, 10) | |
| self.assertEqual(reader_ocr.search_reader_ocr_pages(pages, needle, page_no, page_size), | |
| reference(pages, needle, page_no, page_size)) | |
| def test_unusual_search_inputs_keep_per_match_side_effects_and_errors(self): | |
| class ObservedText(str): | |
| def __new__(cls, value): | |
| result = super().__new__(cls, value) | |
| result.calls = 0 | |
| return result | |
| def find(self, needle, start=0): | |
| self.calls += 1 | |
| return super().find(needle, start) | |
| def count(self, *args): | |
| raise AssertionError("custom count must not be called") | |
| folded = ObservedText("a" * 20) | |
| sample = [{"page": 1, "text": "a" * 20, "folded": folded, "fold_map": None, | |
| "spans": [], "layout": {}}] | |
| total, hits = reader_ocr.search_reader_ocr_pages(sample, "a", 1, 3) | |
| self.assertEqual((total, len(hits), folded.calls), (20, 3, 21)) | |
| self.assertEqual(reader_ocr.search_reader_ocr_pages(sample, "a", 0, 0), (20, [])) | |
| folded2 = ObservedText("aaa") | |
| sample2 = [{**sample[0], "text": "aaa", "folded": folded2}] | |
| self.assertEqual(reader_ocr.search_reader_ocr_pages(sample2, ObservedText("a"), 1, 1)[0], 3) | |
| self.assertEqual(folded2.calls, 4) | |
| malformed = [{"page": 1, "text": "ß", "folded": "ss", "fold_map": [0], | |
| "spans": [], "layout": {}}] | |
| with self.assertRaises(IndexError): | |
| reader_ocr.search_reader_ocr_pages(malformed, "ss", 1, 1) | |
| def test_metadata_and_page_order_are_validated_before_search(self): | |
| valid = book([page()]) | |
| variants = [[], {}, {**valid, "version": 1}, {**valid, "kind": "other"}, | |
| {**valid, "complete": False}, {**valid, "offset_unit": "utf16"}, | |
| {**valid, "page_count": 2}, {**valid, "source_sha256": "x" * 64}, | |
| book([None]), book([page(0)]), book([page(2), page(1)]), book([page(1), page(1)]), | |
| book([{**page(), "text": None}]), book([{**page(), "layout": {}}]), | |
| book([{**page(), "text_spans": None}])] | |
| for payload in variants: | |
| with self.subTest(payload=payload), self.assertRaises(ValueError): | |
| app.parse_reader_ocr_book(encode(payload)) | |
| def test_rejects_invalid_and_overlapping_spans_and_out_of_range_boxes(self): | |
| valid = {"start": 0, "end": 2, "box": [0, .1, .8, 1]} | |
| invalid = [None, {}, {**valid, "start": -1}, {**valid, "end": 0}, | |
| {**valid, "end": 6}, {**valid, "box": [0, 1, 2, 0]}, | |
| {**valid, "box": [0, 1, 0]}, {**valid, "box": [0, 1, 0, "bad"]}] | |
| for span in invalid: | |
| with self.subTest(span=span), self.assertRaises(ValueError): | |
| app.parse_reader_ocr_book(encode(book([page(spans=[span])]))) | |
| with self.assertRaises(ValueError): | |
| app.parse_reader_ocr_book(encode(book([page(spans=[valid, {**valid, "start": 1, "end": 3}])]))) | |
| def test_size_limit_applies_to_decompressed_content(self): | |
| payload = encode(book([page(text="é")])) | |
| from unittest.mock import patch | |
| with patch.object(app, "READER_RESOURCE_MAX_BYTES", 1): | |
| with self.assertRaisesRegex(ValueError, "too large"): | |
| app.parse_reader_ocr_book(payload) | |
| def test_casefold_map_memory_counts_toward_later_page_limit(self): | |
| from unittest.mock import patch | |
| raw = encode(book([page(index + 1, "ß" * 1000) for index in range(100)])) | |
| with patch.object(app, "READER_RESOURCE_MAX_BYTES", 250000): | |
| with self.assertRaisesRegex(ValueError, "too large"): | |
| app.parse_reader_ocr_book(raw) | |
| def test_original_offsets_and_boxes_survive_fold_expansion_and_pagination(self): | |
| spans = [{"start": 0, "end": 2, "box": [0, 0, .2, 1]}, | |
| {"start": 2, "end": 3, "box": [.2, 0, .3, 1]}] | |
| pages, _ = app.parse_reader_ocr_book(encode(book([page(text="ßßx", spans=spans)]))) | |
| total, hits = app.search_reader_ocr_pages(pages, "s", 2, 2) | |
| self.assertEqual(total, 4) | |
| self.assertEqual([(hit["start"], hit["length"]) for hit in hits], [(1, 1), (1, 1)]) | |
| self.assertEqual(hits[0]["boxes"], [[0, 0, .2, 1]]) | |
| self.assertEqual(app.search_reader_ocr_pages(pages, "", 1, 10), (0, [])) | |
| def test_legacy_page_without_fold_map_recomputes_original_offsets(self): | |
| pages = [{"page": 3, "text": "Straße", "folded": "strasse", "spans": [], "layout": {}}] | |
| total, hits = app.search_reader_ocr_pages(pages, "ss", 1, 10) | |
| self.assertEqual(total, 1) | |
| self.assertEqual((hits[0]["page"], hits[0]["start"], hits[0]["length"]), (3, 4, 1)) | |
| def test_full_result_page_does_not_visit_every_remaining_match(self): | |
| # Dense OCR results must not turn a bounded first-page request into | |
| # Python work per later match. Do not require a particular count API. | |
| import sys | |
| text = 'a' * 256 | |
| pages = [{'page': number, 'text': text, 'folded': text, 'fold_map': None, | |
| 'layout': {}, 'spans': []} for number in (1, 2)] | |
| search = reader_ocr.search_reader_ocr_pages | |
| previous = sys.getprofile() | |
| work_calls = 0 | |
| def profile(frame, event, _argument): | |
| nonlocal work_calls | |
| name = frame.f_code.co_name | |
| is_search = name == 'search_reader_ocr_pages' or name.startswith('x_search_reader_ocr_pages__mutmut_') | |
| if event in ('call', 'c_call') and frame.f_code.co_filename == reader_ocr.__file__ and is_search: | |
| work_calls += 1 | |
| try: | |
| sys.setprofile(profile) | |
| total, hits = search(pages, 'a', 1, 1) | |
| finally: | |
| sys.setprofile(previous) | |
| self.assertEqual(total, 512) | |
| self.assertEqual([(hit['page'], hit['start'], hit['length']) for hit in hits], [(1, 0, 1)]) | |
| self.assertLess(work_calls, 256) | |
| def test_ocr_index_decompression_is_limited_even_on_rejection(self): | |
| limit = 256 | |
| raw = encode({**book([]), 'unused': 'x' * 2048}) | |
| reads = [] | |
| original_gzip_file = gzip.GzipFile | |
| class RecordingGzipFile(original_gzip_file): | |
| def read(self, size=-1): | |
| reads.append(size) | |
| return super().read(size) | |
| with patch.object(reader_ocr.gzip, 'GzipFile', RecordingGzipFile): | |
| with self.assertRaisesRegex(ValueError, '^PDF OCR text index is too large$'): | |
| reader_ocr.parse_reader_ocr_book(raw, limit) | |
| self.assertEqual(reads, [limit + 1]) | |
| def test_ocr_count_keeps_page_size_subclass_comparison_side_effects(self): | |
| class ObservedPageSize(int): | |
| def __new__(cls, value): | |
| result = super().__new__(cls, value) | |
| result.comparisons = 0 | |
| return result | |
| def __eq__(self, other): | |
| self.comparisons += 1 | |
| return super().__eq__(other) | |
| size = ObservedPageSize(1) | |
| pages = [{'page': 1, 'text': 'aaaaa', 'folded': 'aaaaa', 'fold_map': None, | |
| 'layout': {}, 'spans': []}] | |
| total, hits = reader_ocr.search_reader_ocr_pages(pages, 'a', 1, size) | |
| self.assertEqual(total, 5) | |
| self.assertEqual([(hit['page'], hit['start'], hit['length']) for hit in hits], [(1, 0, 1)]) | |
| self.assertEqual(size.comparisons, 0) | |
| def test_custom_needle_length_retains_nonoverlapping_per_match_count(self): | |
| class ObservedNeedle(str): | |
| def __new__(cls, value): | |
| result = super().__new__(cls, value) | |
| result.length_calls = 0 | |
| return result | |
| def __len__(self): | |
| self.length_calls += 1 | |
| return 2 | |
| needle = ObservedNeedle('a') | |
| sample = [{'page': 1, 'text': 'aaaaa', 'folded': 'aaaaa', 'fold_map': None, | |
| 'layout': {}, 'spans': []}] | |
| total, hits = reader_ocr.search_reader_ocr_pages(sample, needle, 1, 1) | |
| self.assertEqual(total, 3) | |
| self.assertEqual([(hit['page'], hit['start'], hit['length']) for hit in hits], [(1, 0, 2)]) | |
| self.assertEqual(needle.length_calls, 1) | |
| def test_ocr_count_keeps_page_number_subclass_offset_comparisons(self): | |
| class ObservedOffset(int): | |
| def __new__(cls, value): | |
| result = super().__new__(cls, value) | |
| result.comparisons = [] | |
| return result | |
| def __mul__(self, other): | |
| return self | |
| def __le__(self, other): | |
| self.comparisons.append(other) | |
| return super().__le__(other) | |
| class ObservedPage(int): | |
| def __new__(cls, value): | |
| result = super().__new__(cls, value) | |
| result.offset = ObservedOffset(value - 1) | |
| return result | |
| def __sub__(self, other): | |
| return self.offset | |
| page_number = ObservedPage(1) | |
| pages = [{'page': 1, 'text': 'aaaaa', 'folded': 'aaaaa', 'fold_map': None, | |
| 'layout': {}, 'spans': []}] | |
| total, hits = reader_ocr.search_reader_ocr_pages(pages, 'a', page_number, 1) | |
| self.assertEqual(total, 5) | |
| self.assertEqual([(hit['page'], hit['start'], hit['length']) for hit in hits], [(1, 0, 1)]) | |
| self.assertEqual(page_number.offset.comparisons, [0, 1, 2, 3, 4]) | |
| def test_search_snippet_boundaries_and_nonoverlapping_boxes(self): | |
| text = 'x' * 100 + 'needle' + 'y' * 100 | |
| boxes = [[0, 0, .1, 1], [.1, 0, .8, 1], [.8, 0, 1, 1]] | |
| spans = [{'start': 0, 'end': 100, 'box': boxes[0]}, | |
| {'start': 100, 'end': 106, 'box': boxes[1]}, | |
| {'start': 106, 'end': len(text), 'box': boxes[2]}] | |
| pages, _ = reader_ocr.parse_reader_ocr_book(encode(book([page(text=text, spans=spans)])), 10000) | |
| total, hits = reader_ocr.search_reader_ocr_pages(pages, 'needle', 1, 10) | |
| self.assertEqual(total, 1) | |
| self.assertEqual(hits, [{'page': 1, 'start': 100, 'length': 6, 'snippet': text[28:194], | |
| 'snippet_start': 72, 'boxes': [boxes[1]]}]) | |
| def test_span_lookup_threshold_preserves_unicode_bounds_and_box_order(self): | |
| minimum = reader_ocr._SPAN_BISECT_MIN | |
| for count in (minimum - 1, minimum, minimum + 1): | |
| with self.subTest(span_count=count): | |
| text = 'x ' * count + 'ß中 !' | |
| start = 2 * count | |
| spans = [{'start': 2 * i, 'end': 2 * i + 2, 'box': [0, 0, .25, 1]} | |
| for i in range(count - 3)] | |
| spans.extend([{'start': start - 1, 'end': start, 'box': [.25, 0, .5, 1]}, | |
| {'start': start, 'end': start + 1, 'box': [.5, 0, .75, 1]}, | |
| {'start': start + 1, 'end': start + 2, 'box': [.75, 0, 1, 1]}]) | |
| pages, _ = app.parse_reader_ocr_book(encode(book([page(text=text, spans=spans)]))) | |
| search = reader_ocr.search_reader_ocr_pages | |
| with patch.object(reader_ocr, 'bisect_right', wraps=reader_ocr.bisect_right) as lower, \ | |
| patch.object(reader_ocr, 'bisect_left', wraps=reader_ocr.bisect_left) as upper: | |
| # 's' touches both neighbors; neither should be returned. '!' is in a gap. | |
| for needle, number, offset, length, expected in ( | |
| ('s', 2, start, 1, [spans[-2]['box']]), | |
| ('ss中', 1, start, 2, [spans[-2]['box'], spans[-1]['box']]), | |
| ('!', 1, start + 3, 1, []), | |
| ): | |
| total, hits = search(pages, needle, number, 1) | |
| self.assertEqual(total, 2 if needle == 's' else 1) | |
| self.assertEqual([(hit['start'], hit['length'], hit['boxes']) for hit in hits], | |
| [(offset, length, expected)]) | |
| self.assertEqual((lower.call_count, upper.call_count), | |
| (3, 3) if count >= minimum else (0, 0)) | |
| def test_unchecked_spans_keep_order_overlap_and_iterable_behavior(self): | |
| count = reader_ocr._SPAN_BISECT_MIN | |
| text = 'a' * count | |
| normal_box, early_box, late_box = [0, 0, 1, 1], [.5, 0, 1, 1], [.25, 0, 1, 1] | |
| spans = [{'start': i, 'end': i + 1, 'box': normal_box} for i in range(count)] | |
| spans.insert(0, {'start': 1, 'end': 3, 'box': early_box}) | |
| spans[-1] = {'start': 0, 'end': count, 'box': late_box} | |
| expected = (count, [{'page': 1, 'start': 1, 'length': 1, 'snippet': text, | |
| 'snippet_start': 1, 'boxes': [early_box, normal_box, late_box]}]) | |
| class SpanIterable: | |
| def __iter__(self): | |
| return iter(spans) | |
| def __class__(self): | |
| raise AssertionError('unchecked callers only require span iteration') | |
| for unchecked in (spans, iter(spans), SpanIterable()): | |
| pages = [{'page': 1, 'text': text, 'folded': text, 'fold_map': None, | |
| 'layout': {}, 'spans': unchecked}] | |
| self.assertEqual(reader_ocr.search_reader_ocr_pages(pages, 'a', 2, 1), expected) | |
| def test_dense_parsed_bounds_are_immutable_and_custom_scalars_keep_scan(self): | |
| count = reader_ocr._SPAN_BISECT_MIN | |
| spans = [{'start': i, 'end': i + 1, 'box': [0, 0, 1, 1]} for i in range(count)] | |
| pages, _ = app.parse_reader_ocr_book(encode(book([page(text='a' * count, spans=spans)]))) | |
| ordered = pages[0]['spans'] | |
| with self.assertRaises(TypeError): | |
| ordered[0] = ordered[-1] | |
| with self.assertRaises(AttributeError): | |
| ordered[0].start = count | |
| class Bound(int): | |
| def __lt__(self, other): | |
| comparisons.append(('start', other)) | |
| return super().__lt__(other) | |
| def __gt__(self, other): | |
| comparisons.append(('end', other)) | |
| return super().__gt__(other) | |
| def __add__(self, other): | |
| return Bound(int(self) + other) | |
| for custom_index, expected in ( | |
| (0, [('start', value) for value in range(1, count + 1)]), | |
| (1, [('start', count)] + [('end', value) for value in range(count)]), | |
| ): | |
| with self.subTest(bound_index=custom_index): | |
| comparisons = [] | |
| mapping = list(range(count)) | |
| mapping[custom_index] = Bound(custom_index) | |
| pages[0]['fold_map'] = mapping | |
| total, hits = reader_ocr.search_reader_ocr_pages(pages, 'aa', 1, 1) | |
| self.assertEqual((total, hits[0]['start'], hits[0]['length'], hits[0]['boxes']), | |
| (count // 2, 0, 2, [spans[0]['box'], spans[1]['box']])) | |
| self.assertEqual(comparisons, expected) | |
| def test_parsed_book_preserves_fold_map_layout_and_size_boundary(self): | |
| original = book([page(text='Straße')]) | |
| decoded = json.dumps(original, ensure_ascii=False).encode() | |
| raw = gzip.compress(decoded) | |
| try: | |
| pages, size = reader_ocr.parse_reader_ocr_book(raw, len(decoded)) | |
| except ValueError as exc: | |
| self.fail(f'an OCR index exactly at the decoded size limit must be accepted: {exc!r}') | |
| self.assertEqual(size, len('Straße'.encode()) + 7 * 4) | |
| self.assertIn('layout', pages[0]) | |
| self.assertIn('fold_map', pages[0]) | |
| self.assertEqual(pages[0]['layout'], {'offset_unit': 'unicode-codepoint'}) | |
| self.assertEqual(list(pages[0]['fold_map']), [0, 1, 2, 3, 4, 4, 5]) | |
| self.assertEqual(reader_ocr.search_reader_ocr_pages(pages, 'ss', 1, 1)[0], 1) | |
| with self.assertRaisesRegex(ValueError, '^PDF OCR text index is too large$'): | |
| reader_ocr.parse_reader_ocr_book(raw, len(decoded) - 1) | |
| def test_search_subclass_receives_strictly_advancing_find_offsets(self): | |
| class ObservedText(str): | |
| def __new__(cls, text): | |
| value = super().__new__(cls, text) | |
| value.offsets = [] | |
| return value | |
| def find(self, needle, start=0): | |
| self.offsets.append(start) | |
| if (not isinstance(start, int) or start < 0 | |
| or len(self.offsets) > 5 | |
| or len(self.offsets) > 1 and start <= self.offsets[-2]): | |
| raise AssertionError('search must advance the next find offset') | |
| return super().find(needle, start) | |
| folded = ObservedText('aaaaa') | |
| pages = [{'page': 1, 'text': 'aaaaa', 'folded': folded, 'fold_map': None, | |
| 'layout': {}, 'spans': []}] | |
| total, hits = reader_ocr.search_reader_ocr_pages(pages, 'aa', 1, 0) | |
| self.assertEqual((total, hits), (2, [])) | |
| self.assertEqual(folded.offsets, [0, 2, 4]) | |
| def test_count_does_not_bypass_custom_folded_find_after_results_fill(self): | |
| class ObservedText(str): | |
| def __new__(cls, text): | |
| result = super().__new__(cls, text) | |
| result.offsets = [] | |
| result.count_calls = 0 | |
| return result | |
| def find(self, needle, start=0): | |
| self.offsets.append(start) | |
| return super().find(needle, start) | |
| def count(self, *args): | |
| self.count_calls += 1 | |
| return -10 | |
| folded = ObservedText('aaaaa') | |
| pages = [{'page': 1, 'text': 'aa', 'folded': 'aa', 'fold_map': None, | |
| 'layout': {}, 'spans': []}, | |
| {'page': 2, 'text': 'aaaaa', 'folded': folded, 'fold_map': None, | |
| 'layout': {}, 'spans': []}] | |
| total, hits = reader_ocr.search_reader_ocr_pages(pages, 'aa', 1, 1) | |
| self.assertEqual(total, 3) | |
| self.assertEqual([(hit['page'], hit['start'], hit['length']) for hit in hits], [(1, 0, 2)]) | |
| self.assertEqual(folded.offsets, [0, 2, 4]) | |
| self.assertEqual(folded.count_calls, 0) | |
| def test_invalid_page_and_span_coordinate_types_raise_validation_errors(self): | |
| valid_span = {'start': 0, 'end': 2, 'box': [0, 0, 1, 1]} | |
| cases = { | |
| 'page-string': book([page('1')]), | |
| 'page-none': book([page(None)]), | |
| 'start-string': book([page(spans=[{**valid_span, 'start': '0'}])]), | |
| 'start-none': book([page(spans=[{**valid_span, 'start': None}])]), | |
| 'end-string': book([page(spans=[{**valid_span, 'end': '2'}])]), | |
| 'end-none': book([page(spans=[{**valid_span, 'end': None}])]), | |
| } | |
| for name, payload in cases.items(): | |
| with self.subTest(case=name): | |
| try: | |
| reader_ocr.parse_reader_ocr_book(encode(payload), 10000) | |
| except ValueError: | |
| pass | |
| except Exception as exc: | |
| self.fail(f'invalid coordinates must raise ValueError, not {type(exc).__name__}: {exc}') | |
| else: | |
| self.fail('invalid coordinates must be rejected') | |
| def test_page_count_limit_is_inclusive_and_checked_before_pages(self): | |
| # Identical invalid entries keep this synthetic boundary fixture small: | |
| # at the limit the first page is validated, above it no page is visited. | |
| for count, expected in ((200000, '^invalid PDF OCR text page$'), | |
| (200001, '^invalid PDF OCR text index$')): | |
| with self.subTest(count=count): | |
| payload = encode(book([None] * count)) | |
| with self.assertRaisesRegex(ValueError, expected): | |
| reader_ocr.parse_reader_ocr_book(payload, 5 * 1024 * 1024) | |
| def test_later_page_text_accepts_exact_accounted_size_limit(self): | |
| folded_text = 'ß' * 200 | |
| _, fold_map = reader_ocr.fold_reader_ocr_text(folded_text) | |
| self.assertIsNotNone(fold_map) | |
| pages = [page(1, folded_text), page(2, 'end')] | |
| accounted = len(folded_text.encode('utf-8')) + len(fold_map) * fold_map.itemsize + len('end') | |
| decoded = json.dumps(book(pages), ensure_ascii=False).encode() | |
| self.assertLess(len(decoded), accounted - 1) | |
| raw = gzip.compress(decoded) | |
| try: | |
| accepted, size = reader_ocr.parse_reader_ocr_book(raw, accounted) | |
| except ValueError as exc: | |
| self.fail(f'accounted bytes exactly at the limit must be accepted: {exc!r}') | |
| self.assertEqual((size, [item['page'] for item in accepted]), (accounted, [1, 2])) | |
| with self.assertRaisesRegex(ValueError, '^PDF OCR text index is too large$'): | |
| reader_ocr.parse_reader_ocr_book(raw, accounted - 1) | |
| def test_legacy_page_without_fold_map_uses_direct_offsets_for_same_length_text(self): | |
| text = 'Alpha Beta Alpha' | |
| box = [0, 0, .5, 1] | |
| legacy = {'page': 4, 'text': text, 'folded': text.casefold(), | |
| 'spans': [{'start': 11, 'end': 16, 'box': box}], 'layout': {}} | |
| pages = [legacy] | |
| try: | |
| total, hits = reader_ocr.search_reader_ocr_pages(pages, 'alpha', 1, 10) | |
| except (IndexError, TypeError, ValueError) as exc: | |
| self.fail(f'legacy same-length text must use direct offsets: {exc!r}') | |
| self.assertEqual(total, 2) | |
| self.assertEqual([(hit['page'], hit['start'], hit['length'], hit['boxes']) for hit in hits], | |
| [(4, 0, 5, []), (4, 11, 5, [box])]) | |
| self.assertNotIn('fold_map', legacy) | |
| class ReaderOcrRouteTests(unittest.IsolatedAsyncioTestCase): | |
| async def test_cancelled_ocr_search_keeps_slot_until_the_worker_exits(self): | |
| import threading | |
| root = 'derived/test/' + 'c' * 32 | |
| manifest = root + '/ocr-manifest.json' | |
| resolved = JSONResponse({'ocr_manifest': '/api/reader-bucket-resource?path=' + manifest}) | |
| manifest_bytes = json.dumps({'book_text': {'path': root + '/ocr/book-text.json.gz'}}).encode() | |
| state = SimpleNamespace(reader_ocr_search_semaphore=asyncio.Semaphore(1)) | |
| entered, release = asyncio.Event(), threading.Event() | |
| loop = asyncio.get_running_loop() | |
| def search(*args): | |
| loop.call_soon_threadsafe(entered.set) | |
| release.wait(3) | |
| return 0, [] | |
| with patch.object(app, 'app', SimpleNamespace(state=state)), \ | |
| patch.object(app, 'api_reader_resolve', AsyncMock(return_value=resolved)), \ | |
| patch.object(app, 'get_reader_bucket_resource', AsyncMock(return_value=manifest_bytes)), \ | |
| patch.object(app, 'get_reader_ocr_book', AsyncMock(return_value=[])), \ | |
| patch.object(app, 'search_reader_ocr_pages', side_effect=search) as worker: | |
| first = asyncio.create_task(app.api_reader_ocr_search('a' * 13, 'a', 1, 5)) | |
| await asyncio.wait_for(entered.wait(), 1) | |
| first.cancel() | |
| try: | |
| with self.assertRaises(asyncio.CancelledError): | |
| await first | |
| self.assertTrue(state.reader_ocr_search_semaphore.locked()) | |
| self.assertEqual(len(state.reader_ocr_workers), 1) | |
| second = asyncio.create_task(app.api_reader_ocr_search('a' * 13, 'b', 1, 5)) | |
| await asyncio.sleep(0) | |
| self.assertFalse(second.done()) | |
| self.assertEqual(worker.call_count, 1) | |
| finally: | |
| release.set() | |
| self.assertEqual((await asyncio.wait_for(second, 2)).status_code, 200) | |
| self.assertFalse(state.reader_ocr_workers) | |
| async def test_resolution_error_is_forwarded_without_reading_the_bucket(self): | |
| failure = JSONResponse({"error": "unknown id"}, status_code=404) | |
| with patch.object(app, "api_reader_resolve", AsyncMock(return_value=failure)), \ | |
| patch.object(app, "get_reader_bucket_resource", AsyncMock()) as bucket: | |
| response = await app.api_reader_ocr_search("a" * 13, "term", 1, 10) | |
| self.assertIs(response, failure) | |
| bucket.assert_not_awaited() | |
| async def test_manifest_validation_rejects_untrusted_or_corrupt_paths(self): | |
| root = "derived/test/" + "a" * 32 | |
| manifest = root + "/ocr-manifest.json" | |
| url = "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + manifest | |
| for bad_url in ("https://example.org/not-reader?path=" + manifest, | |
| "/api/reader-bucket-resource?path=" + manifest + "&extra=1", | |
| "/api/reader-bucket-resource?path=../../ocr-manifest.json", | |
| "/api/reader-bucket-resource?path=" + root + "/not-a-manifest.json"): | |
| with self.subTest(url=bad_url), \ | |
| patch.object(app, "api_reader_resolve", AsyncMock(return_value=JSONResponse({"ocr_manifest": bad_url}))), \ | |
| patch.object(app, "get_reader_bucket_resource", AsyncMock()) as bucket: | |
| response = await app.api_reader_ocr_search("a" * 13, "x", 1, 5) | |
| self.assertEqual(response.status_code, 404) | |
| bucket.assert_not_awaited() | |
| for payload in ([], {}, {"book_text": {}}, {"book_text": {"path": "../book-text.json.gz"}}, | |
| {"book_text": {"path": root + "/wrong.json.gz"}}): | |
| with self.subTest(payload=payload), \ | |
| patch.object(app, "api_reader_resolve", AsyncMock(return_value=JSONResponse({"ocr_manifest": url}))), \ | |
| patch.object(app, "get_reader_bucket_resource", AsyncMock(return_value=json.dumps(payload).encode())), \ | |
| patch.object(app, "get_reader_ocr_book", AsyncMock()) as load: | |
| response = await app.api_reader_ocr_search("a" * 13, "x", 1, 5) | |
| self.assertEqual(response.status_code, 502) | |
| load.assert_not_awaited() | |
| async def test_invalid_manifest_json_returns_corruption_error(self): | |
| manifest = "derived/test/" + "a" * 32 + "/ocr-manifest.json" | |
| url = "/api/reader-bucket-resource?path=" + manifest | |
| with patch.object(app, "api_reader_resolve", AsyncMock(return_value=JSONResponse({"ocr_manifest": url}))), \ | |
| patch.object(app, "get_reader_bucket_resource", AsyncMock(return_value=b"not json")): | |
| response = await app.api_reader_ocr_search("a" * 13, "x", 1, 5) | |
| self.assertEqual(response.status_code, 502) | |
| self.assertEqual(json.loads(response.body), {"error": "OCR 索引损坏"}) | |
| async def test_dense_ocr_route_reuses_validated_spans_from_cache(self): | |
| count = reader_ocr._SPAN_BISECT_MIN | |
| root = 'derived/test/' + 'c' * 32 | |
| manifest = root + '/ocr-manifest.json' | |
| book_path = root + '/ocr/book-text.json.gz' | |
| resolved = JSONResponse({'ocr_manifest': '/api/reader-bucket-resource?path=' + manifest}) | |
| text = 'ß' * count | |
| spans = [{'start': i, 'end': i + 1, 'box': [i / count, 0, 1, 1]} for i in range(count)] | |
| payload = encode(book([page(text=text, spans=spans)])) | |
| manifest_bytes = json.dumps({'book_text': {'path': book_path}}).encode() | |
| state = SimpleNamespace() | |
| with patch.object(app, 'app', SimpleNamespace(state=state)), \ | |
| patch.object(app, 'api_reader_resolve', AsyncMock(return_value=resolved)), \ | |
| patch.object(app, 'get_reader_bucket_resource', AsyncMock( | |
| side_effect=[manifest_bytes, payload, manifest_bytes])) as bucket, \ | |
| patch.object(reader_ocr, 'bisect_right', wraps=reader_ocr.bisect_right) as lower: | |
| for number, offset in ((1, 0), (2, 1)): | |
| response = await app.api_reader_ocr_search('a' * 13, 'ß', number, 1) | |
| self.assertEqual(response.status_code, 200) | |
| self.assertEqual(response.headers['cache-control'], 'no-store') | |
| data = json.loads(response.body) | |
| self.assertEqual((data['page'], data['page_size'], data['total']), (number, 1, count)) | |
| self.assertEqual([(hit['start'], hit['length'], hit['boxes']) for hit in data['results']], | |
| [(offset, 1, [spans[offset]['box']])]) | |
| self.assertEqual(lower.call_count, 2) | |
| self.assertEqual([call.args for call in bucket.await_args_list], [(manifest,), (book_path,), (manifest,)]) | |
| self.assertEqual(state.reader_ocr_cache_bytes, len(text.encode()) + 2 * count * 4) | |
| async def test_ocr_cache_hit_refreshes_lru_and_expiry_reloads_once(self): | |
| original, fresh = [{"page": 1}], [{"page": 2}] | |
| current = time.monotonic() | |
| state = SimpleNamespace(reader_ocr_cache=OrderedDict([ | |
| ("book", (current, original, 5)), ("other", (current, [], 7))]), | |
| reader_ocr_cache_bytes=12, reader_ocr_inflight={}) | |
| with patch.object(app, "app", SimpleNamespace(state=state)), \ | |
| patch.object(app, "_load_reader_ocr_book", AsyncMock(return_value=fresh)) as load: | |
| self.assertIs(await app.get_reader_ocr_book("book"), original) | |
| self.assertEqual(list(state.reader_ocr_cache), ["other", "book"]) | |
| load.assert_not_awaited() | |
| state.reader_ocr_cache["book"] = (current - app.READER_BUCKET_CACHE_TTL_SECONDS - 1, original, 5) | |
| with patch.object(app, "app", SimpleNamespace(state=state)), \ | |
| patch.object(app, "_load_reader_ocr_book", AsyncMock(return_value=fresh)) as load: | |
| self.assertIs(await app.get_reader_ocr_book("book"), fresh) | |
| self.assertNotIn("book", state.reader_ocr_cache) | |
| self.assertEqual(state.reader_ocr_cache_bytes, 7) | |
| load.assert_awaited_once_with("book") | |
| async def test_cancelled_subscriber_does_not_cancel_shared_ocr_parse(self): | |
| state = SimpleNamespace() | |
| started, release = asyncio.Event(), asyncio.Event() | |
| pages = [{"page": 1}] | |
| async def load(_path): | |
| started.set() | |
| await release.wait() | |
| return pages | |
| with patch.object(app, "app", SimpleNamespace(state=state)), \ | |
| patch.object(app, "_load_reader_ocr_book", side_effect=load) as loader: | |
| first = asyncio.create_task(app.get_reader_ocr_book("book")) | |
| await asyncio.wait_for(started.wait(), 1) | |
| second = asyncio.create_task(app.get_reader_ocr_book("book")) | |
| try: | |
| await asyncio.sleep(0) | |
| first.cancel() | |
| with self.assertRaises(asyncio.CancelledError): | |
| await first | |
| self.assertFalse(second.done()) | |
| finally: | |
| release.set() | |
| self.assertIs(await asyncio.wait_for(second, 1), pages) | |
| await asyncio.sleep(0) | |
| self.assertEqual(state.reader_ocr_inflight, {}) | |
| loader.assert_awaited_once_with("book") | |
| async def test_failed_shared_ocr_parse_is_not_cached_and_can_retry(self): | |
| state = SimpleNamespace() | |
| started, release = asyncio.Event(), asyncio.Event() | |
| invalid = ValueError("synthetic corrupt index") | |
| fresh = [{"page": 1}] | |
| attempts = 0 | |
| async def load(_path): | |
| nonlocal attempts | |
| attempts += 1 | |
| if attempts == 1: | |
| started.set() | |
| await release.wait() | |
| raise invalid | |
| return fresh | |
| with patch.object(app, "app", SimpleNamespace(state=state)), \ | |
| patch.object(app, "_load_reader_ocr_book", side_effect=load) as loader: | |
| first = asyncio.create_task(app.get_reader_ocr_book("book")) | |
| await asyncio.wait_for(started.wait(), 1) | |
| second = asyncio.create_task(app.get_reader_ocr_book("book")) | |
| try: | |
| await asyncio.sleep(0) | |
| self.assertFalse(first.done()) | |
| self.assertFalse(second.done()) | |
| finally: | |
| release.set() | |
| outcomes = await asyncio.wait_for(asyncio.gather(first, second, return_exceptions=True), 1) | |
| self.assertEqual(len(outcomes), 2) | |
| self.assertIs(outcomes[0], invalid) | |
| self.assertIs(outcomes[1], invalid) | |
| self.assertEqual(state.reader_ocr_inflight, {}) | |
| self.assertEqual(state.reader_ocr_cache, {}) | |
| self.assertEqual(state.reader_ocr_cache_bytes, 0) | |
| loader.assert_awaited_once_with("book") | |
| self.assertIs(await asyncio.wait_for(app.get_reader_ocr_book("book"), 1), fresh) | |
| self.assertEqual(loader.await_count, 2) | |
| self.assertEqual(state.reader_ocr_inflight, {}) | |
| async def test_invalid_ocr_bytes_are_not_published_before_successful_retry(self): | |
| state = SimpleNamespace() | |
| valid = encode(book([page(text="Retry text")])) | |
| bucket = AsyncMock(side_effect=[b"not a gzip stream", valid]) | |
| with patch.object(app, "app", SimpleNamespace(state=state)), \ | |
| patch.object(app, "get_reader_bucket_resource", bucket): | |
| with self.assertRaises(gzip.BadGzipFile): | |
| await asyncio.wait_for(app.get_reader_ocr_book("book"), 2) | |
| self.assertEqual(state.reader_ocr_inflight, {}) | |
| self.assertEqual(state.reader_ocr_cache, {}) | |
| self.assertEqual(state.reader_ocr_cache_bytes, 0) | |
| pages = await asyncio.wait_for(app.get_reader_ocr_book("book"), 2) | |
| self.assertEqual([(item["page"], item["text"]) for item in pages], [(1, "Retry text")]) | |
| self.assertEqual(state.reader_ocr_cache_bytes, len("Retry text".encode())) | |
| self.assertIs(state.reader_ocr_cache["book"][1], pages) | |
| self.assertEqual(state.reader_ocr_inflight, {}) | |
| self.assertIs(await app.get_reader_ocr_book("book"), pages) | |
| self.assertEqual(bucket.await_count, 2) | |
| async def test_oversized_parsed_book_does_not_enter_ocr_cache(self): | |
| pages = [{"page": 1}] | |
| state = SimpleNamespace(reader_ocr_cache=OrderedDict(), reader_ocr_cache_bytes=0) | |
| with patch.object(app, "app", SimpleNamespace(state=state)), \ | |
| patch.object(app, "get_reader_bucket_resource", AsyncMock(return_value=b"data")), \ | |
| patch.object(app, "parse_reader_ocr_book", return_value=(pages, 101)), \ | |
| patch.object(app, "READER_OCR_CACHE_MAX_BYTES", 100): | |
| self.assertIs(await app._load_reader_ocr_book("book"), pages) | |
| self.assertEqual(state.reader_ocr_cache, {}) | |
| self.assertEqual(state.reader_ocr_cache_bytes, 0) | |
| async def test_parsed_book_refresh_replaces_cached_size_and_evicts_oldest(self): | |
| prior = [{'page': 1}] | |
| fresh = [{'page': 2}] | |
| state = SimpleNamespace(reader_ocr_cache=OrderedDict([ | |
| ('book', (1.0, prior, 5)), ('other', (1.0, prior, 4))]), | |
| reader_ocr_cache_bytes=9) | |
| with patch.object(app, 'app', SimpleNamespace(state=state)), \ | |
| patch.object(app, 'get_reader_bucket_resource', AsyncMock(return_value=b'synthetic')) as bucket, \ | |
| patch.object(app, 'parse_reader_ocr_book', return_value=(fresh, 3)) as parse, \ | |
| patch.object(app, 'READER_OCR_CACHE_MAX_BYTES', 6), \ | |
| patch.object(app, 'READER_OCR_CACHE_MAX_ITEMS', 2): | |
| try: | |
| loaded = await app._load_reader_ocr_book('book') | |
| except KeyError as exc: | |
| self.fail(f'cache eviction must not exhaust its entries: {exc}') | |
| self.assertIs(loaded, fresh) | |
| bucket.assert_awaited_once_with('book') | |
| parse.assert_called_once_with(b'synthetic') | |
| self.assertEqual(list(state.reader_ocr_cache), ['book']) | |
| self.assertEqual(state.reader_ocr_cache['book'][1:], (fresh, 3)) | |
| self.assertEqual(state.reader_ocr_cache_bytes, 3) | |
| if __name__ == "__main__": | |
| unittest.main() | |