pyocr-toolkit 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyocr_toolkit/__init__.py +3 -0
- pyocr_toolkit/__main__.py +3 -0
- pyocr_toolkit/api.py +603 -0
- pyocr_toolkit/cli.py +315 -0
- pyocr_toolkit/compare.py +142 -0
- pyocr_toolkit/config.py +86 -0
- pyocr_toolkit/credentials.py +108 -0
- pyocr_toolkit/documents.py +326 -0
- pyocr_toolkit/env.example +48 -0
- pyocr_toolkit/jobs.py +205 -0
- pyocr_toolkit/llm/__init__.py +44 -0
- pyocr_toolkit/llm/anthropic_provider.py +188 -0
- pyocr_toolkit/llm/base.py +126 -0
- pyocr_toolkit/llm/catalog.py +337 -0
- pyocr_toolkit/llm/gemini_provider.py +98 -0
- pyocr_toolkit/llm/openai_provider.py +183 -0
- pyocr_toolkit/llm/prompts.py +61 -0
- pyocr_toolkit/search.py +88 -0
- pyocr_toolkit/service.py +269 -0
- pyocr_toolkit/static/common.js +538 -0
- pyocr_toolkit/static/compare.js +157 -0
- pyocr_toolkit/static/document.js +89 -0
- pyocr_toolkit/static/jobs.js +13 -0
- pyocr_toolkit/static/library.js +28 -0
- pyocr_toolkit/static/models.js +98 -0
- pyocr_toolkit/static/providers.js +44 -0
- pyocr_toolkit/static/reader.js +78 -0
- pyocr_toolkit/static/search.js +34 -0
- pyocr_toolkit/static/styles.css +819 -0
- pyocr_toolkit/static/workspace.js +420 -0
- pyocr_toolkit/static/workspaces.js +81 -0
- pyocr_toolkit/templates/_doc_card.html +30 -0
- pyocr_toolkit/templates/_doctabs.html +14 -0
- pyocr_toolkit/templates/_icons.html +55 -0
- pyocr_toolkit/templates/_llm_picker.html +12 -0
- pyocr_toolkit/templates/base.html +97 -0
- pyocr_toolkit/templates/compare.html +84 -0
- pyocr_toolkit/templates/document.html +80 -0
- pyocr_toolkit/templates/error.html +11 -0
- pyocr_toolkit/templates/help.html +244 -0
- pyocr_toolkit/templates/home.html +90 -0
- pyocr_toolkit/templates/jobs.html +15 -0
- pyocr_toolkit/templates/library.html +44 -0
- pyocr_toolkit/templates/models.html +67 -0
- pyocr_toolkit/templates/providers.html +104 -0
- pyocr_toolkit/templates/reader.html +28 -0
- pyocr_toolkit/templates/search.html +22 -0
- pyocr_toolkit/templates/workspace.html +109 -0
- pyocr_toolkit/templates/workspace_detail.html +42 -0
- pyocr_toolkit/templates/workspaces.html +42 -0
- pyocr_toolkit/web.py +186 -0
- pyocr_toolkit/workspaces.py +330 -0
- pyocr_toolkit-0.3.0.dist-info/METADATA +483 -0
- pyocr_toolkit-0.3.0.dist-info/RECORD +57 -0
- pyocr_toolkit-0.3.0.dist-info/WHEEL +4 -0
- pyocr_toolkit-0.3.0.dist-info/entry_points.txt +3 -0
- pyocr_toolkit-0.3.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""Document storage and everything that touches PyMuPDF.
|
|
2
|
+
|
|
3
|
+
A "document" is any file PyMuPDF can open: PDF, XPS, EPUB, CBZ, FB2, MOBI,
|
|
4
|
+
SVG and raster images (PNG, JPEG, TIFF, BMP, GIF, ...). Raster images open as
|
|
5
|
+
a single-page document (multi-frame TIFFs as several pages), so the rest of
|
|
6
|
+
the app never needs to special-case them.
|
|
7
|
+
|
|
8
|
+
On disk, each upload lives in its own folder::
|
|
9
|
+
|
|
10
|
+
data/documents/<doc_id>/
|
|
11
|
+
meta.json # filename, page count, ...
|
|
12
|
+
source.<ext> # the original bytes, untouched
|
|
13
|
+
ocr/<page>.json # cached Tesseract result (text + word boxes)
|
|
14
|
+
llm/<page>/<key>.json # cached LLM transcriptions
|
|
15
|
+
|
|
16
|
+
Page numbers are **0-based** everywhere in the Python/HTTP API; the UI adds 1
|
|
17
|
+
when displaying them.
|
|
18
|
+
|
|
19
|
+
PyMuPDF objects are not thread-safe, and FastAPI runs sync endpoints in a
|
|
20
|
+
thread pool, so every access to an open ``pymupdf.Document`` goes through a
|
|
21
|
+
per-document lock.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import hashlib
|
|
27
|
+
import json
|
|
28
|
+
import re
|
|
29
|
+
import shutil
|
|
30
|
+
import threading
|
|
31
|
+
import time
|
|
32
|
+
import uuid
|
|
33
|
+
from collections import OrderedDict
|
|
34
|
+
from collections.abc import Iterator
|
|
35
|
+
from dataclasses import asdict, dataclass, field
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
from typing import Any
|
|
38
|
+
|
|
39
|
+
import pymupdf
|
|
40
|
+
|
|
41
|
+
# Extensions PyMuPDF understands. Used to give the file a proper suffix so
|
|
42
|
+
# PyMuPDF picks the right parser, and to reject obviously wrong uploads early.
|
|
43
|
+
SUPPORTED_EXTENSIONS = {
|
|
44
|
+
".pdf", ".xps", ".oxps", ".epub", ".cbz", ".cbr", ".fb2", ".mobi", ".svg", ".txt",
|
|
45
|
+
".png", ".jpg", ".jpeg", ".jpx", ".jp2", ".bmp", ".gif", ".tif", ".tiff",
|
|
46
|
+
".pnm", ".pgm", ".pbm", ".ppm", ".pam", ".psd", ".webp",
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
_DOC_ID_RE = re.compile(r"^[0-9a-f]{32}$")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class DocumentError(Exception):
|
|
53
|
+
"""Raised for user-facing problems (bad file, unknown id, bad page)."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class OCRUnavailableError(DocumentError):
|
|
57
|
+
"""Raised when Tesseract is not installed / not found by PyMuPDF."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class DocumentMeta:
|
|
62
|
+
id: str
|
|
63
|
+
filename: str
|
|
64
|
+
page_count: int
|
|
65
|
+
filetype: str
|
|
66
|
+
is_pdf: bool
|
|
67
|
+
size_bytes: int
|
|
68
|
+
created_at: float
|
|
69
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class Word:
|
|
74
|
+
x0: float
|
|
75
|
+
y0: float
|
|
76
|
+
x1: float
|
|
77
|
+
y1: float
|
|
78
|
+
text: str
|
|
79
|
+
block: int
|
|
80
|
+
line: int
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def rect(self) -> list[float]:
|
|
84
|
+
return [round(self.x0, 2), round(self.y0, 2), round(self.x1, 2), round(self.y1, 2)]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class TextLayer:
|
|
89
|
+
"""Text of one page from one engine, plus word boxes in PDF points."""
|
|
90
|
+
|
|
91
|
+
source: str # "native" | "ocr"
|
|
92
|
+
text: str
|
|
93
|
+
words: list[Word]
|
|
94
|
+
elapsed_ms: float | None = None
|
|
95
|
+
|
|
96
|
+
def to_json(self) -> dict[str, Any]:
|
|
97
|
+
return {
|
|
98
|
+
"source": self.source,
|
|
99
|
+
"text": self.text,
|
|
100
|
+
"elapsed_ms": self.elapsed_ms,
|
|
101
|
+
"words": [[*w.rect, w.text, w.block, w.line] for w in self.words],
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def from_json(cls, data: dict[str, Any]) -> TextLayer:
|
|
106
|
+
words = [Word(*row[:4], text=row[4], block=row[5], line=row[6]) for row in data["words"]]
|
|
107
|
+
return cls(source=data["source"], text=data["text"], words=words, elapsed_ms=data.get("elapsed_ms"))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _words_from_page(page: pymupdf.Page, textpage: pymupdf.TextPage | None = None) -> list[Word]:
|
|
111
|
+
raw = page.get_text("words", textpage=textpage, sort=True)
|
|
112
|
+
return [Word(x0, y0, x1, y1, text, block, line) for (x0, y0, x1, y1, text, block, line, _wno) in raw]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class OpenDocument:
|
|
116
|
+
"""A stored document with a lazily opened PyMuPDF handle."""
|
|
117
|
+
|
|
118
|
+
def __init__(self, folder: Path, meta: DocumentMeta) -> None:
|
|
119
|
+
self.folder = folder
|
|
120
|
+
self.meta = meta
|
|
121
|
+
self._lock = threading.RLock()
|
|
122
|
+
self._doc: pymupdf.Document | None = None
|
|
123
|
+
|
|
124
|
+
# -- lifecycle -----------------------------------------------------------
|
|
125
|
+
@property
|
|
126
|
+
def source_path(self) -> Path:
|
|
127
|
+
return next(self.folder.glob("source.*"))
|
|
128
|
+
|
|
129
|
+
def _handle(self) -> pymupdf.Document:
|
|
130
|
+
if self._doc is None or self._doc.is_closed:
|
|
131
|
+
self._doc = pymupdf.open(self.source_path)
|
|
132
|
+
return self._doc
|
|
133
|
+
|
|
134
|
+
def close(self) -> None:
|
|
135
|
+
with self._lock:
|
|
136
|
+
if self._doc is not None and not self._doc.is_closed:
|
|
137
|
+
self._doc.close()
|
|
138
|
+
self._doc = None
|
|
139
|
+
|
|
140
|
+
def _page(self, number: int) -> pymupdf.Page:
|
|
141
|
+
if not 0 <= number < self.meta.page_count:
|
|
142
|
+
raise DocumentError(f"page {number} out of range (document has {self.meta.page_count} pages)")
|
|
143
|
+
return self._handle()[number]
|
|
144
|
+
|
|
145
|
+
# -- page info / rendering ----------------------------------------------
|
|
146
|
+
def page_info(self, number: int) -> dict[str, Any]:
|
|
147
|
+
with self._lock:
|
|
148
|
+
page = self._page(number)
|
|
149
|
+
text = page.get_text()
|
|
150
|
+
image_count = len(page.get_images(full=False))
|
|
151
|
+
native_chars = len(text.strip())
|
|
152
|
+
return {
|
|
153
|
+
"number": number,
|
|
154
|
+
"width": round(page.rect.width, 2),
|
|
155
|
+
"height": round(page.rect.height, 2),
|
|
156
|
+
"rotation": page.rotation,
|
|
157
|
+
"native_chars": native_chars,
|
|
158
|
+
"image_count": image_count,
|
|
159
|
+
# A page with images but (almost) no text layer is almost
|
|
160
|
+
# certainly a scan and needs OCR to be searchable. Raster
|
|
161
|
+
# uploads (PNG/JPEG/...) never have a text layer.
|
|
162
|
+
"looks_scanned": (native_chars < 20 and image_count > 0) or native_chars == 0,
|
|
163
|
+
"has_ocr_cache": self._ocr_cache_path(number).exists(),
|
|
164
|
+
"llm_results": len(list(self._llm_dir(number).glob("*.json"))),
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
def render(self, number: int, dpi: int, fmt: str = "png", max_edge_px: int | None = None,
|
|
168
|
+
jpg_quality: int = 90) -> bytes:
|
|
169
|
+
"""Rasterise a page. ``fmt`` is ``png`` or ``jpeg``."""
|
|
170
|
+
with self._lock:
|
|
171
|
+
page = self._page(number)
|
|
172
|
+
if max_edge_px:
|
|
173
|
+
# Pick the largest DPI <= requested that keeps the long edge in bounds.
|
|
174
|
+
long_edge_pt = max(page.rect.width, page.rect.height)
|
|
175
|
+
dpi = max(36, min(dpi, int(max_edge_px * 72 / long_edge_pt)))
|
|
176
|
+
pix = page.get_pixmap(dpi=dpi, alpha=False)
|
|
177
|
+
if fmt == "jpeg":
|
|
178
|
+
return pix.tobytes("jpeg", jpg_quality=jpg_quality)
|
|
179
|
+
return pix.tobytes("png")
|
|
180
|
+
|
|
181
|
+
# -- text layers ----------------------------------------------------------
|
|
182
|
+
def native_text(self, number: int) -> TextLayer:
|
|
183
|
+
"""Text that is already embedded in the file (no OCR)."""
|
|
184
|
+
with self._lock:
|
|
185
|
+
page = self._page(number)
|
|
186
|
+
t0 = time.perf_counter()
|
|
187
|
+
text = page.get_text("text", sort=True)
|
|
188
|
+
words = _words_from_page(page)
|
|
189
|
+
return TextLayer("native", text, words, elapsed_ms=round((time.perf_counter() - t0) * 1000, 1))
|
|
190
|
+
|
|
191
|
+
def _ocr_cache_path(self, number: int) -> Path:
|
|
192
|
+
return self.folder / "ocr" / f"{number}.json"
|
|
193
|
+
|
|
194
|
+
def ocr_text(self, number: int, *, dpi: int, language: str, force: bool = False) -> TextLayer:
|
|
195
|
+
"""Tesseract OCR via PyMuPDF. Results are cached on disk because OCR is slow."""
|
|
196
|
+
cache = self._ocr_cache_path(number)
|
|
197
|
+
if cache.exists() and not force:
|
|
198
|
+
return TextLayer.from_json(json.loads(cache.read_text()))
|
|
199
|
+
with self._lock:
|
|
200
|
+
page = self._page(number)
|
|
201
|
+
t0 = time.perf_counter()
|
|
202
|
+
try:
|
|
203
|
+
# full=True OCRs the whole page image, ignoring any existing text
|
|
204
|
+
# layer: that is what we want when judging OCR quality.
|
|
205
|
+
tp = page.get_textpage_ocr(full=True, dpi=dpi, language=language)
|
|
206
|
+
except RuntimeError as exc: # raised when tesseract / tessdata is missing
|
|
207
|
+
raise OCRUnavailableError(
|
|
208
|
+
f"Tesseract OCR is not available ({exc}). Install tesseract-ocr and the "
|
|
209
|
+
f"'{language}' language pack, or set TESSDATA_PREFIX."
|
|
210
|
+
) from exc
|
|
211
|
+
text = page.get_text("text", textpage=tp, sort=True)
|
|
212
|
+
words = _words_from_page(page, textpage=tp)
|
|
213
|
+
layer = TextLayer("ocr", text, words, elapsed_ms=round((time.perf_counter() - t0) * 1000, 1))
|
|
214
|
+
cache.parent.mkdir(parents=True, exist_ok=True)
|
|
215
|
+
cache.write_text(json.dumps(layer.to_json()))
|
|
216
|
+
return layer
|
|
217
|
+
|
|
218
|
+
def cached_ocr_text(self, number: int) -> TextLayer | None:
|
|
219
|
+
cache = self._ocr_cache_path(number)
|
|
220
|
+
return TextLayer.from_json(json.loads(cache.read_text())) if cache.exists() else None
|
|
221
|
+
|
|
222
|
+
# -- LLM result cache -----------------------------------------------------
|
|
223
|
+
def _llm_dir(self, number: int) -> Path:
|
|
224
|
+
return self.folder / "llm" / str(number)
|
|
225
|
+
|
|
226
|
+
@staticmethod
|
|
227
|
+
def llm_cache_key(provider: str, model: str, prompt: str) -> str:
|
|
228
|
+
digest = hashlib.sha256(f"{provider}\0{model}\0{prompt}".encode()).hexdigest()[:16]
|
|
229
|
+
safe_model = re.sub(r"[^A-Za-z0-9._-]+", "_", model)[:60]
|
|
230
|
+
return f"{provider}__{safe_model}__{digest}"
|
|
231
|
+
|
|
232
|
+
def save_llm_result(self, number: int, key: str, result: dict[str, Any]) -> None:
|
|
233
|
+
folder = self._llm_dir(number)
|
|
234
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
235
|
+
(folder / f"{key}.json").write_text(json.dumps(result, ensure_ascii=False, indent=1))
|
|
236
|
+
|
|
237
|
+
def load_llm_result(self, number: int, key: str) -> dict[str, Any] | None:
|
|
238
|
+
path = self._llm_dir(number) / f"{key}.json"
|
|
239
|
+
return json.loads(path.read_text()) if path.exists() else None
|
|
240
|
+
|
|
241
|
+
def list_llm_results(self, number: int) -> list[dict[str, Any]]:
|
|
242
|
+
results = []
|
|
243
|
+
for path in self._llm_dir(number).glob("*.json"):
|
|
244
|
+
data = json.loads(path.read_text())
|
|
245
|
+
data["key"] = path.stem
|
|
246
|
+
results.append(data)
|
|
247
|
+
return sorted(results, key=lambda r: r.get("created_at", 0), reverse=True)
|
|
248
|
+
|
|
249
|
+
def iter_pages(self) -> Iterator[int]:
|
|
250
|
+
return iter(range(self.meta.page_count))
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class DocumentStore:
|
|
254
|
+
"""Persists uploads under ``root`` and hands out :class:`OpenDocument` objects."""
|
|
255
|
+
|
|
256
|
+
def __init__(self, root: Path, max_open: int = 16) -> None:
|
|
257
|
+
self.root = Path(root)
|
|
258
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
259
|
+
self._open: OrderedDict[str, OpenDocument] = OrderedDict()
|
|
260
|
+
self._max_open = max_open
|
|
261
|
+
self._lock = threading.Lock()
|
|
262
|
+
|
|
263
|
+
def add(self, filename: str, data: bytes) -> DocumentMeta:
|
|
264
|
+
ext = Path(filename).suffix.lower() or ".pdf"
|
|
265
|
+
if ext not in SUPPORTED_EXTENSIONS:
|
|
266
|
+
raise DocumentError(f"unsupported file type '{ext}'")
|
|
267
|
+
try:
|
|
268
|
+
doc = pymupdf.open(stream=data, filetype=ext.lstrip("."))
|
|
269
|
+
except Exception as exc: # PyMuPDF raises several exception types here
|
|
270
|
+
raise DocumentError(f"could not open '{filename}': {exc}") from exc
|
|
271
|
+
try:
|
|
272
|
+
if doc.needs_pass:
|
|
273
|
+
raise DocumentError("document is password protected")
|
|
274
|
+
if doc.page_count == 0:
|
|
275
|
+
raise DocumentError("document has no pages")
|
|
276
|
+
meta = DocumentMeta(
|
|
277
|
+
id=uuid.uuid4().hex,
|
|
278
|
+
filename=Path(filename).name,
|
|
279
|
+
page_count=doc.page_count,
|
|
280
|
+
filetype=ext.lstrip("."),
|
|
281
|
+
is_pdf=doc.is_pdf,
|
|
282
|
+
size_bytes=len(data),
|
|
283
|
+
created_at=time.time(),
|
|
284
|
+
metadata={k: v for k, v in (doc.metadata or {}).items() if v},
|
|
285
|
+
)
|
|
286
|
+
finally:
|
|
287
|
+
doc.close()
|
|
288
|
+
folder = self.root / meta.id
|
|
289
|
+
folder.mkdir(parents=True)
|
|
290
|
+
(folder / f"source{ext}").write_bytes(data)
|
|
291
|
+
(folder / "meta.json").write_text(json.dumps(asdict(meta), indent=1))
|
|
292
|
+
return meta
|
|
293
|
+
|
|
294
|
+
def get(self, doc_id: str) -> OpenDocument:
|
|
295
|
+
if not _DOC_ID_RE.match(doc_id):
|
|
296
|
+
raise DocumentError("unknown document")
|
|
297
|
+
with self._lock:
|
|
298
|
+
if doc_id in self._open:
|
|
299
|
+
self._open.move_to_end(doc_id)
|
|
300
|
+
return self._open[doc_id]
|
|
301
|
+
folder = self.root / doc_id
|
|
302
|
+
meta_path = folder / "meta.json"
|
|
303
|
+
if not meta_path.exists():
|
|
304
|
+
raise DocumentError("unknown document")
|
|
305
|
+
doc = OpenDocument(folder, DocumentMeta(**json.loads(meta_path.read_text())))
|
|
306
|
+
self._open[doc_id] = doc
|
|
307
|
+
while len(self._open) > self._max_open:
|
|
308
|
+
_, evicted = self._open.popitem(last=False)
|
|
309
|
+
evicted.close()
|
|
310
|
+
return doc
|
|
311
|
+
|
|
312
|
+
def list(self) -> list[DocumentMeta]:
|
|
313
|
+
metas = []
|
|
314
|
+
for meta_path in self.root.glob("*/meta.json"):
|
|
315
|
+
try:
|
|
316
|
+
metas.append(DocumentMeta(**json.loads(meta_path.read_text())))
|
|
317
|
+
except (ValueError, TypeError):
|
|
318
|
+
continue
|
|
319
|
+
return sorted(metas, key=lambda m: m.created_at, reverse=True)
|
|
320
|
+
|
|
321
|
+
def delete(self, doc_id: str) -> None:
|
|
322
|
+
doc = self.get(doc_id)
|
|
323
|
+
with self._lock:
|
|
324
|
+
self._open.pop(doc_id, None)
|
|
325
|
+
doc.close()
|
|
326
|
+
shutil.rmtree(doc.folder)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# pyocr-toolkit settings. Run `pyocr init` to copy this file to .env, then fill in
|
|
2
|
+
# the providers you use. Providers without credentials show as "not configured".
|
|
3
|
+
# Keys are read by the server only; they are never sent to the browser.
|
|
4
|
+
|
|
5
|
+
# --- Claude (Anthropic API) ---------------------------------------------------
|
|
6
|
+
ANTHROPIC_API_KEY=
|
|
7
|
+
# ANTHROPIC_MODEL=claude-opus-5-5
|
|
8
|
+
# How much the model reasons before answering: low | medium | high | xhigh | max
|
|
9
|
+
# ANTHROPIC_EFFORT=medium
|
|
10
|
+
|
|
11
|
+
# --- OpenAI -------------------------------------------------------------------
|
|
12
|
+
OPENAI_API_KEY=
|
|
13
|
+
# OPENAI_MODEL=gpt-6.2-sol
|
|
14
|
+
# OPENAI_BASE_URL=
|
|
15
|
+
|
|
16
|
+
# --- Azure OpenAI ---------------------------------------------------------------
|
|
17
|
+
AZURE_OPENAI_API_KEY=
|
|
18
|
+
# AZURE_OPENAI_ENDPOINT=https://<resource>.openai.azure.com
|
|
19
|
+
# AZURE_OPENAI_DEPLOYMENT=<a vision-capable deployment name>
|
|
20
|
+
# AZURE_OPENAI_API_VERSION=2024-10-21
|
|
21
|
+
|
|
22
|
+
# --- Claude on Azure (Microsoft Foundry) ------------------------------------------
|
|
23
|
+
ANTHROPIC_FOUNDRY_API_KEY=
|
|
24
|
+
# ANTHROPIC_FOUNDRY_RESOURCE=<foundry-resource-name>
|
|
25
|
+
# or the full endpoint instead of the resource name:
|
|
26
|
+
# ANTHROPIC_FOUNDRY_BASE_URL=https://<resource>.services.ai.azure.com/anthropic
|
|
27
|
+
# ANTHROPIC_FOUNDRY_MODEL=claude-opus-5-5
|
|
28
|
+
|
|
29
|
+
# --- Google Gemini --------------------------------------------------------------
|
|
30
|
+
GEMINI_API_KEY=
|
|
31
|
+
# GEMINI_MODEL=gemini-3.8-flash
|
|
32
|
+
|
|
33
|
+
# --- Any OpenAI-compatible server: Ollama, vLLM, LM Studio, OpenRouter ----------
|
|
34
|
+
# OPENAI_COMPATIBLE_BASE_URL=http://localhost:11434/v1
|
|
35
|
+
# OPENAI_COMPATIBLE_MODEL=qwen2.5vl:7b
|
|
36
|
+
# OPENAI_COMPATIBLE_API_KEY=
|
|
37
|
+
|
|
38
|
+
# --- Storage, rendering and OCR ---------------------------------------------------
|
|
39
|
+
# DATA_DIR=data
|
|
40
|
+
# MAX_UPLOAD_MB=200
|
|
41
|
+
# PREVIEW_DPI=110
|
|
42
|
+
# LLM_DPI=200
|
|
43
|
+
# LLM_MAX_EDGE_PX=2400
|
|
44
|
+
# OCR_DPI=300
|
|
45
|
+
# TESSERACT_LANGUAGE=eng # e.g. eng+deu (install the language packs first)
|
|
46
|
+
# LLM_CONCURRENCY=4
|
|
47
|
+
# LLM_TIMEOUT_S=300
|
|
48
|
+
# USD_INR_RATE=92.5 # rupees per dollar, for showing LLM costs in ₹ (not fetched live)
|
pyocr_toolkit/jobs.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Background extraction jobs ("OCR / transcribe the whole document").
|
|
2
|
+
|
|
3
|
+
A job processes a list of pages with one engine and records progress, so
|
|
4
|
+
the browser can start it, navigate elsewhere, and come back to a progress
|
|
5
|
+
bar. Results are written to the normal per-page caches as each page finishes,
|
|
6
|
+
which means a job that dies half way loses nothing that already completed,
|
|
7
|
+
and re-running it only processes the missing pages.
|
|
8
|
+
|
|
9
|
+
Jobs live in memory: restarting the server forgets the job list (not the
|
|
10
|
+
results).
|
|
11
|
+
|
|
12
|
+
Progress is reported in pages. ``current_pages`` are pages the engine is working
|
|
13
|
+
on right now; LLM pages that are still waiting for an ``LLM_CONCURRENCY`` slot
|
|
14
|
+
(another job or a workspace run holds it) are in ``waiting_pages`` instead, so
|
|
15
|
+
the UI doesn't claim the model is reading a page it hasn't been sent yet.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import asyncio
|
|
21
|
+
import time
|
|
22
|
+
import uuid
|
|
23
|
+
from dataclasses import asdict, dataclass, field
|
|
24
|
+
from typing import Any, Literal
|
|
25
|
+
|
|
26
|
+
from .documents import DocumentStore
|
|
27
|
+
from .llm import catalog
|
|
28
|
+
from .service import LLMSpec, Services
|
|
29
|
+
|
|
30
|
+
JobKind = Literal["ocr", "llm"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class Job:
|
|
35
|
+
id: str
|
|
36
|
+
doc_id: str
|
|
37
|
+
kind: JobKind
|
|
38
|
+
pages: list[int]
|
|
39
|
+
label: str
|
|
40
|
+
llm: dict[str, Any] | None = None
|
|
41
|
+
force: bool = False
|
|
42
|
+
status: str = "queued" # queued | running | done | failed | cancelled
|
|
43
|
+
done: int = 0
|
|
44
|
+
cached: int = 0
|
|
45
|
+
failed: int = 0
|
|
46
|
+
errors: list[str] = field(default_factory=list)
|
|
47
|
+
input_tokens: int = 0
|
|
48
|
+
output_tokens: int = 0
|
|
49
|
+
created_at: float = field(default_factory=time.time)
|
|
50
|
+
started_at: float | None = None
|
|
51
|
+
finished_at: float | None = None
|
|
52
|
+
current_pages: list[int] = field(default_factory=list)
|
|
53
|
+
waiting_pages: list[int] = field(default_factory=list)
|
|
54
|
+
#: catalog list price for LLM jobs: {"in", "out" (USD per 1M tokens), "model", "usd_inr_rate"}; None if unknown
|
|
55
|
+
price: dict[str, Any] | None = None
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def total(self) -> int:
|
|
59
|
+
return len(self.pages)
|
|
60
|
+
|
|
61
|
+
def timing(self, now: float | None = None) -> tuple[float | None, float | None]:
|
|
62
|
+
"""``(seconds_per_page, eta_seconds)`` from the pages processed so far.
|
|
63
|
+
|
|
64
|
+
Cache hits are near-instant, so they're left out of the rate: the rate is
|
|
65
|
+
elapsed time over pages that really ran (failures included, since they
|
|
66
|
+
cost time too). With N workers this is wall time per page, i.e. it already
|
|
67
|
+
accounts for concurrency. Both are ``None`` until a page has really run;
|
|
68
|
+
the ETA is only given while the job is running.
|
|
69
|
+
"""
|
|
70
|
+
if self.started_at is None:
|
|
71
|
+
return None, None
|
|
72
|
+
processed = self.done - self.cached
|
|
73
|
+
if processed <= 0:
|
|
74
|
+
return None, None
|
|
75
|
+
end = self.finished_at or (now if now is not None else time.time())
|
|
76
|
+
per_page = (end - self.started_at) / processed
|
|
77
|
+
eta = per_page * (self.total - self.done) if self.status == "running" else None
|
|
78
|
+
return per_page, eta
|
|
79
|
+
|
|
80
|
+
def cost(self) -> dict[str, Any] | None:
|
|
81
|
+
"""Spend so far at list price, plus a projection for the whole job while it runs.
|
|
82
|
+
|
|
83
|
+
The projection assumes remaining pages cost what the paid pages so far did on
|
|
84
|
+
average; pages that turn out to be cached make the real total lower.
|
|
85
|
+
"""
|
|
86
|
+
if not self.price:
|
|
87
|
+
return None
|
|
88
|
+
usd = (self.input_tokens * self.price["in"] + self.output_tokens * self.price["out"]) / 1_000_000
|
|
89
|
+
rate = self.price["usd_inr_rate"]
|
|
90
|
+
paid = self.done - self.cached - self.failed
|
|
91
|
+
projected = usd / paid * (paid + self.total - self.done) if self.status == "running" and paid > 0 else None
|
|
92
|
+
return {"usd": usd, "inr": usd * rate, "projected_usd": projected,
|
|
93
|
+
"projected_inr": projected * rate if projected is not None else None,
|
|
94
|
+
"usd_inr_rate": rate, "price_in": self.price["in"], "price_out": self.price["out"],
|
|
95
|
+
"price_model": self.price["model"]}
|
|
96
|
+
|
|
97
|
+
def to_json(self) -> dict[str, Any]:
|
|
98
|
+
data = asdict(self)
|
|
99
|
+
data["total"] = self.total
|
|
100
|
+
data["pages"] = len(self.pages)
|
|
101
|
+
data["first_page"] = self.pages[0] if self.pages else None
|
|
102
|
+
data["errors"] = self.errors[-20:]
|
|
103
|
+
data["seconds_per_page"], data["eta_seconds"] = self.timing()
|
|
104
|
+
data["cost"] = self.cost()
|
|
105
|
+
return data
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class JobManager:
|
|
109
|
+
def __init__(self, store: DocumentStore, services: Services, ocr_concurrency: int = 1) -> None:
|
|
110
|
+
self.store = store
|
|
111
|
+
self.services = services
|
|
112
|
+
self.ocr_concurrency = ocr_concurrency
|
|
113
|
+
self.jobs: dict[str, Job] = {}
|
|
114
|
+
self._tasks: dict[str, asyncio.Task] = {}
|
|
115
|
+
|
|
116
|
+
def list(self, doc_id: str | None = None) -> list[Job]:
|
|
117
|
+
jobs = [j for j in self.jobs.values() if doc_id is None or j.doc_id == doc_id]
|
|
118
|
+
return sorted(jobs, key=lambda j: j.created_at, reverse=True)
|
|
119
|
+
|
|
120
|
+
def get(self, job_id: str) -> Job | None:
|
|
121
|
+
return self.jobs.get(job_id)
|
|
122
|
+
|
|
123
|
+
def start(self, doc_id: str, kind: JobKind, pages: list[int], llm: LLMSpec | None = None,
|
|
124
|
+
force: bool = False) -> Job:
|
|
125
|
+
doc = self.store.get(doc_id) # validates the id
|
|
126
|
+
price: dict[str, Any] | None = None
|
|
127
|
+
if kind == "llm":
|
|
128
|
+
if llm is None:
|
|
129
|
+
raise ValueError("LLM job needs a provider")
|
|
130
|
+
provider, model, _ = self.services.resolve_spec(llm)
|
|
131
|
+
if not provider.configured:
|
|
132
|
+
raise ValueError(f"{provider.label} is not configured: set {', '.join(provider.missing_settings())}")
|
|
133
|
+
label = f"LLM · {provider.label} · {model} · {llm.prompt_mode}"
|
|
134
|
+
found = catalog.price(model, provider.id)
|
|
135
|
+
if found:
|
|
136
|
+
price = {"in": found[0], "out": found[1], "model": found[2],
|
|
137
|
+
"usd_inr_rate": self.services.settings.usd_inr_rate}
|
|
138
|
+
else:
|
|
139
|
+
label = f"Tesseract OCR ({self.services.settings.tesseract_language})"
|
|
140
|
+
job = Job(id=uuid.uuid4().hex[:12], doc_id=doc.meta.id, kind=kind, pages=pages, label=label,
|
|
141
|
+
llm=asdict(llm) if llm else None, force=force, price=price)
|
|
142
|
+
self.jobs[job.id] = job
|
|
143
|
+
self._tasks[job.id] = asyncio.get_running_loop().create_task(self._run(job))
|
|
144
|
+
return job
|
|
145
|
+
|
|
146
|
+
def cancel(self, job_id: str) -> Job | None:
|
|
147
|
+
job = self.jobs.get(job_id)
|
|
148
|
+
task = self._tasks.get(job_id)
|
|
149
|
+
if job and task and not task.done():
|
|
150
|
+
task.cancel()
|
|
151
|
+
return job
|
|
152
|
+
|
|
153
|
+
async def _run(self, job: Job) -> None:
|
|
154
|
+
doc = self.store.get(job.doc_id)
|
|
155
|
+
job.status = "running"
|
|
156
|
+
job.started_at = time.time()
|
|
157
|
+
queue: asyncio.Queue[int] = asyncio.Queue()
|
|
158
|
+
for p in job.pages:
|
|
159
|
+
queue.put_nowait(p)
|
|
160
|
+
spec = LLMSpec(**job.llm) if job.llm else None
|
|
161
|
+
|
|
162
|
+
async def worker() -> None:
|
|
163
|
+
while not queue.empty():
|
|
164
|
+
page = queue.get_nowait()
|
|
165
|
+
# LLM pages wait for a semaphore slot before the model sees them.
|
|
166
|
+
(job.waiting_pages if job.kind == "llm" else job.current_pages).append(page)
|
|
167
|
+
|
|
168
|
+
def started(page: int = page) -> None:
|
|
169
|
+
job.waiting_pages.remove(page)
|
|
170
|
+
job.current_pages.append(page)
|
|
171
|
+
|
|
172
|
+
try:
|
|
173
|
+
if job.kind == "ocr":
|
|
174
|
+
if not job.force and doc.cached_ocr_text(page) is not None:
|
|
175
|
+
job.cached += 1
|
|
176
|
+
else:
|
|
177
|
+
await asyncio.to_thread(self.services.run_ocr_page, doc, page, job.force)
|
|
178
|
+
else:
|
|
179
|
+
res = await self.services.run_llm_page(doc, page, spec, force=job.force, on_start=started)
|
|
180
|
+
if res.get("cached"):
|
|
181
|
+
job.cached += 1
|
|
182
|
+
else:
|
|
183
|
+
job.input_tokens += res.get("input_tokens") or 0
|
|
184
|
+
job.output_tokens += res.get("output_tokens") or 0
|
|
185
|
+
except asyncio.CancelledError:
|
|
186
|
+
raise
|
|
187
|
+
except Exception as exc: # keep going; report per page
|
|
188
|
+
job.failed += 1
|
|
189
|
+
job.errors.append(f"page {page + 1}: {exc}")
|
|
190
|
+
finally:
|
|
191
|
+
for active in (job.current_pages, job.waiting_pages):
|
|
192
|
+
if page in active:
|
|
193
|
+
active.remove(page)
|
|
194
|
+
job.done += 1
|
|
195
|
+
|
|
196
|
+
concurrency = self.ocr_concurrency if job.kind == "ocr" else self.services.settings.llm_concurrency
|
|
197
|
+
try:
|
|
198
|
+
await asyncio.gather(*(worker() for _ in range(max(1, min(concurrency, job.total)))))
|
|
199
|
+
job.status = "failed" if job.failed == job.total else "done"
|
|
200
|
+
except asyncio.CancelledError:
|
|
201
|
+
job.status = "cancelled"
|
|
202
|
+
finally:
|
|
203
|
+
job.finished_at = time.time()
|
|
204
|
+
job.current_pages.clear()
|
|
205
|
+
job.waiting_pages.clear()
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""LLM providers that can transcribe a page image."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ..config import Settings
|
|
6
|
+
from . import catalog
|
|
7
|
+
from .anthropic_provider import AnthropicFoundryProvider, AnthropicProvider
|
|
8
|
+
from .base import (
|
|
9
|
+
Provider,
|
|
10
|
+
ProviderError,
|
|
11
|
+
ProviderNotConfigured,
|
|
12
|
+
TranscriptionRequest,
|
|
13
|
+
TranscriptionResult,
|
|
14
|
+
)
|
|
15
|
+
from .gemini_provider import GeminiProvider
|
|
16
|
+
from .openai_provider import AzureOpenAIProvider, OpenAICompatibleProvider, OpenAIProvider
|
|
17
|
+
from .prompts import PROMPT_MODES, USER_PROMPT, resolve_prompt
|
|
18
|
+
|
|
19
|
+
PROVIDER_CLASSES: list[type[Provider]] = [
|
|
20
|
+
AnthropicProvider,
|
|
21
|
+
OpenAIProvider,
|
|
22
|
+
AzureOpenAIProvider,
|
|
23
|
+
AnthropicFoundryProvider,
|
|
24
|
+
GeminiProvider,
|
|
25
|
+
OpenAICompatibleProvider,
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def build_providers(settings: Settings) -> dict[str, Provider]:
|
|
30
|
+
return {cls.id: cls(settings) for cls in PROVIDER_CLASSES}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"catalog",
|
|
35
|
+
"PROMPT_MODES",
|
|
36
|
+
"USER_PROMPT",
|
|
37
|
+
"Provider",
|
|
38
|
+
"ProviderError",
|
|
39
|
+
"ProviderNotConfigured",
|
|
40
|
+
"TranscriptionRequest",
|
|
41
|
+
"TranscriptionResult",
|
|
42
|
+
"build_providers",
|
|
43
|
+
"resolve_prompt",
|
|
44
|
+
]
|