Download backend/reader/query/domain/ocr.py from VoiceOfML/Search: direct link, hf CLI and curl.
- Browser
- Download file 8.8 kB
-
https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/backend/reader/query/domain/ocr.py
- Command line
-
hf download hf://spaces/VoiceOfML/Search/backend/reader/query/domain/ocr.py
-
curl -L -o ocr.py https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/backend/reader/query/domain/ocr.py
8.8 kB
| """Bounded PDF text-index validation and original-offset search.""" | |
| from __future__ import annotations | |
| from array import array | |
| from bisect import bisect_left, bisect_right | |
| import gzip | |
| import io | |
| import json | |
| from operator import attrgetter | |
| import re | |
| from typing import NamedTuple, NotRequired, TypedDict, cast | |
| # Start above the synthetic crossover to leave room for cold conversion cost. | |
| _SPAN_BISECT_MIN = 64 | |
| _SPAN_END = attrgetter("end") | |
| _SPAN_START = attrgetter("start") | |
| class OcrSpan(TypedDict): | |
| start: int | |
| end: int | |
| box: list[int | float] | |
| class _OrderedSpan(NamedTuple): | |
| start: int | |
| end: int | |
| box: list[int | float] | |
| class _ValidatedSpans(tuple[_OrderedSpan, ...]): | |
| """Parser-owned order and bounds, immutable even when a page is shared.""" | |
| __slots__ = () | |
| def overlapping_boxes(self, start: int, end: int) -> list[list[int | float]]: | |
| # Unusual callers can supply custom bounds through folded text or a fold map. | |
| if type(start) is not int or type(end) is not int: | |
| return [span.box for span in self if span.end > start and span.start < end] | |
| # Both keys are monotone. Exclude spans that only touch either bound. | |
| lo = bisect_right(self, start, key=_SPAN_END) | |
| hi = bisect_left(self, end, lo=lo, key=_SPAN_START) | |
| return [span.box for span in self[lo:hi]] | |
| class OcrPage(TypedDict): | |
| page: int | |
| text: str | |
| folded: str | |
| fold_map: NotRequired[array[int] | None] | |
| layout: dict[str, object] | |
| spans: list[OcrSpan] | _ValidatedSpans | |
| class OcrSearchHit(TypedDict): | |
| page: int | |
| start: int | |
| length: int | |
| snippet: str | |
| snippet_start: int | |
| boxes: list[list[int | float]] | |
| def fold_reader_ocr_text(text: str) -> tuple[str, array[int] | None]: | |
| """Map casefold-expanded code points back to the source text.""" | |
| folded = text.casefold() | |
| if len(folded) == len(text): | |
| return folded, None | |
| pieces: list[str] = [] | |
| fold_map: array[int] = array('I') | |
| for index, character in enumerate(text): | |
| piece = character.casefold() | |
| pieces.append(piece) | |
| fold_map.extend([index] * len(piece)) | |
| return "".join(pieces), fold_map | |
| def parse_reader_ocr_book(raw: bytes, max_bytes: int) -> tuple[list[OcrPage], int]: | |
| """Decode and validate one v2 book index without exceeding its byte limit.""" | |
| with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream: | |
| decoded = stream.read(max_bytes + 1) | |
| if len(decoded) > max_bytes: | |
| raise ValueError("PDF OCR text index is too large") | |
| payload: object = json.loads(decoded) | |
| if not isinstance(payload, dict): | |
| raise ValueError("invalid PDF OCR text index") | |
| document = cast(dict[str, object], payload) | |
| raw_pages = document.get("pages") | |
| if not isinstance(raw_pages, list): | |
| raise ValueError("invalid PDF OCR text index") | |
| pages = cast(list[object], raw_pages) | |
| if (len(pages) > 200000 | |
| or document.get("version") != 2 or document.get("kind") != "pdf-book-text" | |
| or document.get("complete") is not True | |
| or document.get("offset_unit") != "unicode-codepoint" | |
| or document.get("page_count") != len(pages) | |
| or not re.fullmatch(r"[0-9a-f]{64}", str(document.get("source_sha256", "")))): | |
| raise ValueError("invalid PDF OCR text index") | |
| output: list[OcrPage] = [] | |
| total_bytes = 0 | |
| previous = 0 | |
| for raw_page in pages: | |
| if not isinstance(raw_page, dict): | |
| raise ValueError("invalid PDF OCR text page") | |
| item = cast(dict[str, object], raw_page) | |
| number, text = item.get("page"), item.get("text") | |
| if (not isinstance(number, int) or number < 1 or number <= previous | |
| or not isinstance(text, str)): | |
| raise ValueError("invalid PDF OCR text page") | |
| total_bytes += len(text.encode("utf-8")) | |
| if total_bytes > max_bytes: | |
| raise ValueError("PDF OCR text index is too large") | |
| layout, spans = item.get("layout"), item.get("text_spans") | |
| if (not isinstance(layout, dict) or cast(dict[str, object], layout).get("offset_unit") != "unicode-codepoint" | |
| or not isinstance(spans, list)): | |
| raise ValueError("invalid PDF text layout mapping") | |
| previous_span_end = 0 | |
| for raw_span in cast(list[object], spans): | |
| if not isinstance(raw_span, dict): | |
| raise ValueError("invalid PDF text span") | |
| span = cast(dict[str, object], raw_span) | |
| start, end, box = span.get("start"), span.get("end"), span.get("box") | |
| if (not isinstance(start, int) or not isinstance(end, int) or start < previous_span_end | |
| or end <= start or end > len(text) or not isinstance(box, list)): | |
| raise ValueError("invalid PDF text span") | |
| values = cast(list[object], box) | |
| if len(values) != 4 or any(not isinstance(value, (int, float)) or value < 0 or value > 1 | |
| for value in values): | |
| raise ValueError("invalid PDF text span") | |
| previous_span_end = end | |
| folded, fold_map = fold_reader_ocr_text(text) | |
| if fold_map is not None: | |
| total_bytes += len(fold_map) * fold_map.itemsize | |
| page_spans: list[OcrSpan] | _ValidatedSpans = cast(list[OcrSpan], spans) | |
| if len(page_spans) >= _SPAN_BISECT_MIN: | |
| # Freeze only the fields needed for dense lookups, reusing the boxes. | |
| page_spans = _ValidatedSpans(_OrderedSpan(span["start"], span["end"], span["box"]) | |
| for span in page_spans) | |
| output.append({"page": number, "text": text, "folded": folded, "fold_map": fold_map, | |
| "layout": cast(dict[str, object], layout), "spans": page_spans}) | |
| previous = number | |
| return output, total_bytes | |
| def search_reader_ocr_pages( | |
| pages: list[OcrPage], needle: str, page: int, page_size: int | |
| ) -> tuple[int, list[OcrSearchHit]]: | |
| """Count all non-overlapping matches; return one page in original offsets.""" | |
| offset = (page - 1) * page_size | |
| end_offset = offset + page_size | |
| folded_length = len(needle) | |
| total = 0 | |
| results: list[OcrSearchHit] = [] | |
| if not folded_length: | |
| return total, results | |
| # Once the requested page is full, only the remaining count is needed. | |
| # Exact built-ins keep custom string methods and unusual callers on the | |
| # existing per-match path, including their errors and side effects. | |
| count_safe = type(needle) is str and type(page) is int and type(page_size) is int and page_size > 0 | |
| for item in pages: | |
| text, folded = item["text"], item["folded"] | |
| if "fold_map" in item: | |
| fold_map = item["fold_map"] | |
| elif len(folded) == len(text): | |
| fold_map = None | |
| else: | |
| folded, fold_map = fold_reader_ocr_text(text) | |
| if count_safe and len(results) == page_size and type(folded) is str: | |
| total += folded.count(needle) | |
| continue | |
| start = 0 | |
| while True: | |
| found = folded.find(needle, start) | |
| if found < 0: | |
| break | |
| match_index = total | |
| total += 1 | |
| if offset <= match_index < end_offset: | |
| if fold_map is None: | |
| original_start, original_end = found, found + folded_length | |
| else: | |
| original_start = fold_map[found] | |
| original_end = fold_map[found + folded_length - 1] + 1 | |
| snippet_start = max(0, original_start - 72) | |
| snippet_end = min(len(text), original_end + 88) | |
| spans = item["spans"] | |
| if type(spans) is _ValidatedSpans: | |
| boxes = spans.overlapping_boxes(original_start, original_end) | |
| else: | |
| # The cast only narrows the type; unchecked callers still just iterate. | |
| unchecked_spans = cast(list[OcrSpan], spans) | |
| boxes = [span["box"] for span in unchecked_spans | |
| if span["end"] > original_start and span["start"] < original_end] | |
| results.append({ | |
| "page": item["page"], "start": original_start, | |
| "length": original_end - original_start, | |
| "snippet": text[snippet_start:snippet_end], | |
| "snippet_start": original_start - snippet_start, "boxes": boxes, | |
| }) | |
| if count_safe and len(results) == page_size and type(folded) is str: | |
| total += folded.count(needle, found + folded_length) | |
| break | |
| start = found + folded_length | |
| return total, results | |