File size: 3,626 Bytes
37fae50
 
 
 
01ab508
37fae50
 
eeb144a
37fae50
 
 
 
 
 
 
01ab508
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37fae50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01ab508
 
 
 
 
 
37fae50
 
 
 
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
"""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,
    }