Download backend/reader/query/application/ocr.py from VoiceOfML/Search: direct link, hf CLI and curl.
- Browser
- Download file 3.63 kB
-
https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/backend/reader/query/application/ocr.py
- Command line
-
hf download hf://spaces/VoiceOfML/Search/backend/reader/query/application/ocr.py
-
curl -L -o ocr.py https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/backend/reader/query/application/ocr.py
3.63 kB
| """Load existing OCR output and run a bounded search; never produce OCR.""" | |
| import asyncio | |
| import json | |
| from collections.abc import Awaitable, Callable | |
| from typing import Protocol, TypeVar, cast | |
| from urllib.parse import ParseResult, parse_qs | |
| from backend.reader.query.domain.ocr import OcrPage, OcrSearchHit | |
| JsonObject = dict[str, object] | |
| OcrSearch = Callable[[list[OcrPage], str, int, int], tuple[int, list[OcrSearchHit]]] | |
| class OcrState(Protocol): | |
| reader_ocr_search_semaphore: asyncio.Semaphore | |
| reader_ocr_workers: set[asyncio.Task[object]] | |
| T = TypeVar("T") | |
| async def run_owned_thread(state: OcrState, compute: Callable[[], T], *, | |
| on_done: Callable[[], None] | None = None) -> T: | |
| if not hasattr(state, "reader_ocr_workers"): | |
| state.reader_ocr_workers = set() | |
| task = asyncio.create_task(asyncio.to_thread(compute)) | |
| tracked = cast(asyncio.Task[object], task) | |
| state.reader_ocr_workers.add(tracked) | |
| def finished(done: asyncio.Task[T]) -> None: | |
| state.reader_ocr_workers.discard(tracked) | |
| if on_done: | |
| on_done() | |
| if not done.cancelled(): | |
| done.exception() | |
| task.add_done_callback(finished) | |
| return await asyncio.shield(task) | |
| class OcrAccess(Protocol): | |
| def parse_url(self, url: str) -> ParseResult: ... | |
| def valid_bucket_path(self, path: str) -> bool: ... | |
| def bucket_resource(self, path: str) -> Awaitable[bytes]: ... | |
| def book(self, path: str) -> Awaitable[list[OcrPage]]: ... | |
| def state(self) -> OcrState: ... | |
| def max_concurrent(self) -> int: ... | |
| def search(self) -> OcrSearch: ... | |
| class MissingOcrIndex(Exception): | |
| """The resolved source has no usable OCR manifest reference.""" | |
| async def search_book(manifest_url: str, q: str, page: int, page_size: int, access: OcrAccess) -> JsonObject: | |
| parsed = access.parse_url(manifest_url) | |
| parameters = parse_qs(parsed.query) | |
| manifest_path = parameters.get("path", [""])[0] | |
| if (parsed.path != "/api/reader-bucket-resource" or set(parameters) != {"path"} | |
| or not access.valid_bucket_path(manifest_path) | |
| or not manifest_path.endswith("/ocr-manifest.json")): | |
| raise MissingOcrIndex | |
| manifest: object = json.loads(await access.bucket_resource(manifest_path)) | |
| book = cast(JsonObject, manifest).get("book_text") if isinstance(manifest, dict) else None | |
| book_path = cast(JsonObject, book).get("path") if isinstance(book, dict) else "" | |
| if (not isinstance(book_path, str) or not access.valid_bucket_path(book_path) | |
| or not book_path.endswith("/book-text.json.gz")): | |
| raise ValueError("invalid OCR book path") | |
| pages = await access.book(book_path) | |
| needle = q.casefold() | |
| # Capture the runtime after loading the book, then the search callable only | |
| # after acquiring its semaphore. Queued work must see a replaced live hook. | |
| state = access.state() | |
| if not hasattr(state, "reader_ocr_search_semaphore"): | |
| state.reader_ocr_search_semaphore = asyncio.Semaphore(access.max_concurrent()) | |
| semaphore = state.reader_ocr_search_semaphore | |
| await semaphore.acquire() | |
| # The hook is resolved after admission, and ownership survives cancelling | |
| # the ASGI waiter while the thread is already executing. | |
| total, results = await run_owned_thread(state, lambda: access.search()(pages, needle, page, page_size), | |
| on_done=semaphore.release) | |
| return { | |
| "version": 2, "kind": "pdf-book-text-search", "page": page, "page_size": page_size, | |
| "total": total, "results": results, | |
| } | |