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.
Files changed (57) hide show
  1. pyocr_toolkit/__init__.py +3 -0
  2. pyocr_toolkit/__main__.py +3 -0
  3. pyocr_toolkit/api.py +603 -0
  4. pyocr_toolkit/cli.py +315 -0
  5. pyocr_toolkit/compare.py +142 -0
  6. pyocr_toolkit/config.py +86 -0
  7. pyocr_toolkit/credentials.py +108 -0
  8. pyocr_toolkit/documents.py +326 -0
  9. pyocr_toolkit/env.example +48 -0
  10. pyocr_toolkit/jobs.py +205 -0
  11. pyocr_toolkit/llm/__init__.py +44 -0
  12. pyocr_toolkit/llm/anthropic_provider.py +188 -0
  13. pyocr_toolkit/llm/base.py +126 -0
  14. pyocr_toolkit/llm/catalog.py +337 -0
  15. pyocr_toolkit/llm/gemini_provider.py +98 -0
  16. pyocr_toolkit/llm/openai_provider.py +183 -0
  17. pyocr_toolkit/llm/prompts.py +61 -0
  18. pyocr_toolkit/search.py +88 -0
  19. pyocr_toolkit/service.py +269 -0
  20. pyocr_toolkit/static/common.js +538 -0
  21. pyocr_toolkit/static/compare.js +157 -0
  22. pyocr_toolkit/static/document.js +89 -0
  23. pyocr_toolkit/static/jobs.js +13 -0
  24. pyocr_toolkit/static/library.js +28 -0
  25. pyocr_toolkit/static/models.js +98 -0
  26. pyocr_toolkit/static/providers.js +44 -0
  27. pyocr_toolkit/static/reader.js +78 -0
  28. pyocr_toolkit/static/search.js +34 -0
  29. pyocr_toolkit/static/styles.css +819 -0
  30. pyocr_toolkit/static/workspace.js +420 -0
  31. pyocr_toolkit/static/workspaces.js +81 -0
  32. pyocr_toolkit/templates/_doc_card.html +30 -0
  33. pyocr_toolkit/templates/_doctabs.html +14 -0
  34. pyocr_toolkit/templates/_icons.html +55 -0
  35. pyocr_toolkit/templates/_llm_picker.html +12 -0
  36. pyocr_toolkit/templates/base.html +97 -0
  37. pyocr_toolkit/templates/compare.html +84 -0
  38. pyocr_toolkit/templates/document.html +80 -0
  39. pyocr_toolkit/templates/error.html +11 -0
  40. pyocr_toolkit/templates/help.html +244 -0
  41. pyocr_toolkit/templates/home.html +90 -0
  42. pyocr_toolkit/templates/jobs.html +15 -0
  43. pyocr_toolkit/templates/library.html +44 -0
  44. pyocr_toolkit/templates/models.html +67 -0
  45. pyocr_toolkit/templates/providers.html +104 -0
  46. pyocr_toolkit/templates/reader.html +28 -0
  47. pyocr_toolkit/templates/search.html +22 -0
  48. pyocr_toolkit/templates/workspace.html +109 -0
  49. pyocr_toolkit/templates/workspace_detail.html +42 -0
  50. pyocr_toolkit/templates/workspaces.html +42 -0
  51. pyocr_toolkit/web.py +186 -0
  52. pyocr_toolkit/workspaces.py +330 -0
  53. pyocr_toolkit-0.3.0.dist-info/METADATA +483 -0
  54. pyocr_toolkit-0.3.0.dist-info/RECORD +57 -0
  55. pyocr_toolkit-0.3.0.dist-info/WHEEL +4 -0
  56. pyocr_toolkit-0.3.0.dist-info/entry_points.txt +3 -0
  57. pyocr_toolkit-0.3.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,3 @@
1
+ """pyocr-toolkit - inspect PDF/image text extraction: native text vs Tesseract OCR vs LLM transcription."""
2
+
3
+ __version__ = "0.3.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
pyocr_toolkit/api.py ADDED
@@ -0,0 +1,603 @@
1
+ """JSON API (under ``/api``) and the application factory.
2
+
3
+ Run with ``pyocr serve`` (or ``uvicorn pyocr_toolkit.api:app``), then open
4
+ http://127.0.0.1:8000. Interactive API docs live at ``/docs``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ import shutil
12
+ from dataclasses import asdict
13
+ from pathlib import Path
14
+ from typing import Literal
15
+
16
+ from fastapi import APIRouter, FastAPI, File, Form, HTTPException, Query, Request, UploadFile
17
+ from fastapi.concurrency import run_in_threadpool
18
+ from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse, Response
19
+ from fastapi.staticfiles import StaticFiles
20
+ from pydantic import BaseModel, Field
21
+
22
+ from . import __version__, compare, search
23
+ from .config import Settings, get_settings
24
+ from .documents import DocumentError, DocumentStore, OCRUnavailableError, OpenDocument
25
+ from .jobs import JobManager
26
+ from .llm import PROMPT_MODES, ProviderError, build_providers, catalog
27
+ from .service import LLMSpec, Services, parse_pages
28
+ from .workspaces import WorkspaceStore, ingest, suggest_names
29
+
30
+ STATIC_DIR = Path(__file__).parent / "static"
31
+
32
+
33
+ # ---------------------------------------------------------------- bodies
34
+ class LLMRunBody(BaseModel):
35
+ provider: str
36
+ model: str | None = None
37
+ prompt_mode: str = "verbatim"
38
+ custom_prompt: str | None = None
39
+ force: bool = False
40
+
41
+ def spec(self) -> LLMSpec:
42
+ return LLMSpec(self.provider, self.model, self.prompt_mode, self.custom_prompt)
43
+
44
+
45
+ class TextRef(BaseModel):
46
+ source: Literal["native", "ocr", "llm"]
47
+ #: for ``llm``: cache key of a stored result (``None`` -> most recent one)
48
+ key: str | None = None
49
+
50
+ @property
51
+ def source_id(self) -> str:
52
+ return f"llm:{self.key}" if self.source == "llm" and self.key else self.source
53
+
54
+
55
+ class CompareBody(BaseModel):
56
+ reference: TextRef = Field(default_factory=lambda: TextRef(source="llm"))
57
+ hypothesis: TextRef = Field(default_factory=lambda: TextRef(source="ocr"))
58
+ ignore_case: bool = False
59
+ ignore_punctuation: bool = False
60
+ diff: bool = True
61
+
62
+
63
+ class JobBody(BaseModel):
64
+ kind: Literal["ocr", "llm"]
65
+ pages: str | None = Field(None, description="1-based page ranges like '1-3,7'; empty = all pages")
66
+ force: bool = False
67
+ llm: LLMRunBody | None = None
68
+
69
+
70
+ class WorkspaceBody(BaseModel):
71
+ name: str | None = Field(None, description="empty = a suggested name such as 'festive-albattani'")
72
+ doc_ids: list[str] = Field(default_factory=list)
73
+
74
+
75
+ class WorkspaceRenameBody(BaseModel):
76
+ name: str
77
+
78
+
79
+ class WorkspaceDocsBody(BaseModel):
80
+ doc_ids: list[str]
81
+
82
+
83
+ class SuggestNamesBody(BaseModel):
84
+ filenames: list[str] = Field(default_factory=list)
85
+ count: int = Field(4, ge=1, le=12)
86
+
87
+
88
+ class ProviderTestBody(BaseModel):
89
+ model: str | None = None
90
+
91
+
92
+ class CredentialsBody(BaseModel):
93
+ #: env var name -> new value; empty / missing = keep the current value
94
+ values: dict[str, str | None] = Field(default_factory=dict)
95
+ #: env var names to forget, falling back to the environment / built-in default
96
+ clear: list[str] = Field(default_factory=list)
97
+
98
+
99
+ def _require_same_origin(request: Request) -> None:
100
+ """Refuse cross-site writes. There's no auth (localhost only), so without this any web
101
+ page open in the same browser could POST new endpoints/keys to the local server."""
102
+ origin = request.headers.get("origin") or request.headers.get("referer")
103
+ if origin:
104
+ from urllib.parse import urlsplit
105
+
106
+ if urlsplit(origin).netloc != request.headers.get("host"):
107
+ raise HTTPException(403, "cross-origin request refused; open pyocr in this browser tab instead")
108
+ if not (request.headers.get("content-type") or "").startswith("application/json"):
109
+ raise HTTPException(415, "send JSON (Content-Type: application/json)")
110
+
111
+
112
+ def _safe_stem(filename: str) -> str:
113
+ # ASCII-only filename: HTTP headers are latin-1 and quotes would break them.
114
+ return re.sub(r"[^A-Za-z0-9._-]+", "_", Path(filename).stem) or "document"
115
+
116
+
117
+ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs: JobManager,
118
+ workspaces: WorkspaceStore) -> APIRouter:
119
+ api = APIRouter(prefix="/api")
120
+ providers = services.providers
121
+
122
+ def get_doc(doc_id: str) -> OpenDocument:
123
+ return store.get(doc_id)
124
+
125
+ def doc_summary(doc: OpenDocument) -> dict:
126
+ """Meta + extraction coverage, used by the library and overview pages."""
127
+ n = doc.meta.page_count
128
+ ocr_pages = llm_pages = 0
129
+ for p in range(n):
130
+ ocr_pages += doc.cached_ocr_text(p) is not None
131
+ llm_pages += bool(doc.list_llm_results(p))
132
+ return {**doc.meta.__dict__, "ocr_pages": ocr_pages, "llm_pages": llm_pages}
133
+
134
+ # ------------------------------------------------------------------ config
135
+ @api.get("/config", tags=["config"])
136
+ def config():
137
+ return {
138
+ "version": __version__,
139
+ "providers": [p.describe() for p in providers.values()],
140
+ "prompt_modes": [{"id": k, "label": v["label"], "prompt": v["system"]} for k, v in PROMPT_MODES.items()],
141
+ "tesseract_available": shutil.which("tesseract") is not None,
142
+ "tesseract_language": settings.tesseract_language,
143
+ "max_upload_mb": settings.max_upload_mb,
144
+ "preview_dpi": settings.preview_dpi,
145
+ "llm_dpi": settings.llm_dpi,
146
+ "ocr_dpi": settings.ocr_dpi,
147
+ }
148
+
149
+ @api.get("/models", tags=["models"])
150
+ def search_models(q: str = "", provider: str | None = None, rating: str | None = None,
151
+ include_deprecated: bool = True):
152
+ """Search the built-in catalog of vision models, rated for page transcription."""
153
+ return {
154
+ "updated": catalog.CATALOG_UPDATED,
155
+ "usd_inr_rate": settings.usd_inr_rate, # prices are USD; the page also shows them in ₹
156
+ "ratings": {k: v[0] for k, v in catalog.RATINGS.items()},
157
+ "sources": [{"label": a, "url": b} for a, b in catalog.SOURCES],
158
+ "models": [m.to_json() for m in catalog.search(q, provider, rating, include_deprecated)],
159
+ }
160
+
161
+ @api.get("/models/lookup", tags=["models"])
162
+ def lookup_model(name: str, provider: str | None = None):
163
+ """How well a (possibly custom) model name suits transcription."""
164
+ return catalog.lookup(name, provider)
165
+
166
+ @api.get("/providers/{provider_id}/models", tags=["models"])
167
+ async def provider_models(provider_id: str, live: bool = True):
168
+ """Catalog models for a provider plus, where the API allows, the models your key can use."""
169
+ try:
170
+ return await services.provider_models(provider_id, live)
171
+ except ValueError as exc:
172
+ raise HTTPException(404, str(exc)) from exc
173
+
174
+ @api.get("/providers/{provider_id}/credentials", tags=["config"])
175
+ def get_credentials(provider_id: str):
176
+ p = providers.get(provider_id)
177
+ if p is None:
178
+ raise HTTPException(404, f"unknown provider '{provider_id}'")
179
+ return {"provider": p.describe(), "settings": services.credentials.status(p)}
180
+
181
+ @api.post("/providers/{provider_id}/credentials", tags=["config"])
182
+ def save_credentials(provider_id: str, body: CredentialsBody, request: Request):
183
+ """Save provider settings from the UI (stored in DATA_DIR/credentials.json, never echoed back)."""
184
+ _require_same_origin(request)
185
+ try:
186
+ services.credentials.update(provider_id, body.values, body.clear)
187
+ except ValueError as exc:
188
+ status = 404 if "unknown provider" in str(exc) else 400
189
+ raise HTTPException(status, str(exc)) from exc
190
+ return get_credentials(provider_id)
191
+
192
+ @api.post("/providers/{provider_id}/test", tags=["config"])
193
+ async def test_provider(provider_id: str, body: ProviderTestBody):
194
+ try:
195
+ return await services.test_provider(provider_id, body.model)
196
+ except ValueError as exc:
197
+ raise HTTPException(404, str(exc)) from exc
198
+
199
+ # --------------------------------------------------------------- documents
200
+ @api.get("/documents", tags=["documents"])
201
+ def list_documents(details: bool = False):
202
+ metas = store.list()
203
+ if not details:
204
+ return [m.__dict__ for m in metas]
205
+ return [doc_summary(store.get(m.id)) for m in metas]
206
+
207
+ @api.post("/documents", status_code=201, tags=["documents"])
208
+ async def upload(file: UploadFile = File(...)):
209
+ data = await file.read()
210
+ if len(data) > settings.max_upload_mb * 1024 * 1024:
211
+ raise HTTPException(413, f"file larger than {settings.max_upload_mb} MB")
212
+ meta = await run_in_threadpool(store.add, file.filename or "upload.pdf", data)
213
+ return meta.__dict__
214
+
215
+ @api.post("/uploads", status_code=201, tags=["documents"])
216
+ async def upload_batch(files: list[UploadFile] = File(...), workspace_id: str | None = Form(None)):
217
+ """Upload several files at once; ``.zip`` archives are unpacked. Optionally add them to a workspace.
218
+
219
+ Files that can't be opened are reported in ``skipped`` instead of failing the whole batch.
220
+ """
221
+ if workspace_id:
222
+ workspaces.get(workspace_id) # fail before storing anything
223
+ max_bytes = settings.max_upload_mb * 1024 * 1024
224
+ named = []
225
+ for f in files:
226
+ data = await f.read(max_bytes + 1)
227
+ named.append((f.filename or "upload.pdf", data))
228
+ result = await run_in_threadpool(ingest, store, named, max_bytes=max_bytes)
229
+ body = result.to_json()
230
+ if workspace_id and result.documents:
231
+ ws = await run_in_threadpool(workspaces.add_documents, workspace_id, [m.id for m in result.documents])
232
+ body["workspace"] = asdict(ws)
233
+ elif workspace_id:
234
+ body["workspace"] = asdict(workspaces.get(workspace_id))
235
+ return body
236
+
237
+ @api.get("/documents/{doc_id}", tags=["documents"])
238
+ def document(doc_id: str):
239
+ return doc_summary(get_doc(doc_id))
240
+
241
+ @api.delete("/documents/{doc_id}", status_code=204, tags=["documents"])
242
+ def delete_document(doc_id: str):
243
+ store.delete(doc_id)
244
+ workspaces.forget_document(doc_id)
245
+ return Response(status_code=204)
246
+
247
+ @api.get("/documents/{doc_id}/source", tags=["documents"])
248
+ def source_file(doc_id: str):
249
+ doc = get_doc(doc_id)
250
+ return FileResponse(doc.source_path, filename=doc.meta.filename)
251
+
252
+ @api.get("/documents/{doc_id}/pages", tags=["pages"])
253
+ def pages(doc_id: str):
254
+ doc = get_doc(doc_id)
255
+ return [doc.page_info(n) for n in doc.iter_pages()]
256
+
257
+ @api.get("/documents/{doc_id}/pages/{page}/image", tags=["pages"])
258
+ def page_image(doc_id: str, page: int, dpi: int = Query(None, ge=36, le=600)):
259
+ png = get_doc(doc_id).render(page, dpi or settings.preview_dpi)
260
+ return Response(png, media_type="image/png", headers={"Cache-Control": "max-age=3600"})
261
+
262
+ @api.get("/documents/{doc_id}/sources", tags=["text"])
263
+ def sources(doc_id: str):
264
+ """Text sources available for the document (native, OCR, each LLM config) with page coverage."""
265
+ return services.list_sources(get_doc(doc_id))
266
+
267
+ # ------------------------------------------------------------- text layers
268
+ @api.get("/documents/{doc_id}/pages/{page}/text/native", tags=["text"])
269
+ def native_text(doc_id: str, page: int):
270
+ return get_doc(doc_id).native_text(page).to_json()
271
+
272
+ @api.get("/documents/{doc_id}/pages/{page}/text/ocr", tags=["text"])
273
+ def ocr_text(doc_id: str, page: int, force: bool = False, cached_only: bool = False):
274
+ doc = get_doc(doc_id)
275
+ if cached_only:
276
+ layer = doc.cached_ocr_text(page)
277
+ return layer.to_json() if layer else None
278
+ return services.run_ocr_page(doc, page, force=force).to_json()
279
+
280
+ @api.get("/documents/{doc_id}/text", tags=["text"])
281
+ def document_text(doc_id: str, source: str = "native"):
282
+ """Every page's text from one source. Missing pages have ``text: null``."""
283
+ doc = get_doc(doc_id)
284
+ return {
285
+ "source": source,
286
+ "label": services.source_label(doc, source),
287
+ "pages": [{"page": n, "text": services.page_text(doc, n, source)} for n in doc.iter_pages()],
288
+ }
289
+
290
+ # --------------------------------------------------------------------- LLM
291
+ @api.get("/documents/{doc_id}/pages/{page}/llm", tags=["llm"])
292
+ def llm_results(doc_id: str, page: int):
293
+ return [services.with_cost(r) for r in get_doc(doc_id).list_llm_results(page)]
294
+
295
+ @api.post("/documents/{doc_id}/pages/{page}/llm", tags=["llm"])
296
+ async def run_llm(doc_id: str, page: int, body: LLMRunBody):
297
+ doc = get_doc(doc_id)
298
+ if not 0 <= page < doc.meta.page_count:
299
+ raise DocumentError(f"page {page} out of range")
300
+ try:
301
+ services.resolve_spec(body.spec())
302
+ except ValueError as exc:
303
+ raise HTTPException(400, str(exc)) from exc
304
+ return services.with_cost(await services.run_llm_page(doc, page, body.spec(), force=body.force))
305
+
306
+ @api.delete("/documents/{doc_id}/pages/{page}/llm/{key}", status_code=204, tags=["llm"])
307
+ def delete_llm_result(doc_id: str, page: int, key: str):
308
+ doc = get_doc(doc_id)
309
+ folder = (doc.folder / "llm" / str(page)).resolve()
310
+ path = (folder / f"{key}.json").resolve()
311
+ if path.parent != folder or not path.exists():
312
+ raise HTTPException(404, "no such result")
313
+ path.unlink()
314
+ return Response(status_code=204)
315
+
316
+ # -------------------------------------------------------------- workspaces
317
+ def ws_json(ws, details: bool = False) -> dict:
318
+ body = asdict(ws)
319
+ metas = [store.get(d).meta for d in ws.doc_ids]
320
+ body["document_count"] = len(metas)
321
+ body["page_count"] = sum(m.page_count for m in metas)
322
+ if details:
323
+ body["documents"] = [doc_summary(store.get(d)) for d in ws.doc_ids]
324
+ return body
325
+
326
+ @api.get("/workspaces", tags=["workspaces"])
327
+ def list_workspaces():
328
+ return [ws_json(w) for w in workspaces.list()]
329
+
330
+ @api.post("/workspaces", status_code=201, tags=["workspaces"])
331
+ def create_workspace(body: WorkspaceBody):
332
+ return ws_json(workspaces.create(body.name, body.doc_ids))
333
+
334
+ @api.post("/workspaces/suggest-names", tags=["workspaces"])
335
+ def suggest_workspace_names(body: SuggestNamesBody):
336
+ """Name ideas in the ``adjective-scientist`` style, led by one taken from the file names if they share one."""
337
+ taken = [w.name for w in workspaces.list()]
338
+ return {"names": suggest_names(body.filenames, taken=taken, count=body.count)}
339
+
340
+ @api.get("/workspaces/{ws_id}", tags=["workspaces"])
341
+ def get_workspace(ws_id: str):
342
+ return ws_json(workspaces.get(ws_id), details=True)
343
+
344
+ @api.patch("/workspaces/{ws_id}", tags=["workspaces"])
345
+ def rename_workspace(ws_id: str, body: WorkspaceRenameBody):
346
+ return ws_json(workspaces.rename(ws_id, body.name))
347
+
348
+ @api.post("/workspaces/{ws_id}/documents", tags=["workspaces"])
349
+ def add_workspace_documents(ws_id: str, body: WorkspaceDocsBody):
350
+ return ws_json(workspaces.add_documents(ws_id, body.doc_ids))
351
+
352
+ @api.delete("/workspaces/{ws_id}/documents/{doc_id}", tags=["workspaces"])
353
+ def remove_workspace_document(ws_id: str, doc_id: str):
354
+ """Take a document out of the workspace. The document itself stays in the library."""
355
+ return ws_json(workspaces.remove_document(ws_id, doc_id))
356
+
357
+ @api.delete("/workspaces/{ws_id}", status_code=204, tags=["workspaces"])
358
+ def delete_workspace(ws_id: str, delete_documents: bool = False):
359
+ workspaces.delete(ws_id, delete_documents=delete_documents)
360
+ return Response(status_code=204)
361
+
362
+ # -------------------------------------------------------------------- jobs
363
+ @api.post("/documents/{doc_id}/jobs", status_code=202, tags=["jobs"])
364
+ async def start_job(doc_id: str, body: JobBody):
365
+ """Extract many pages in the background (OCR or an LLM). Poll ``/api/jobs/{id}``."""
366
+ doc = get_doc(doc_id)
367
+ try:
368
+ pages_list = parse_pages(body.pages, doc.meta.page_count)
369
+ if body.kind == "ocr" and not shutil.which("tesseract"):
370
+ raise ValueError("Tesseract is not installed on the server")
371
+ job = jobs.start(doc.meta.id, body.kind, pages_list,
372
+ llm=body.llm.spec() if body.llm else None, force=body.force)
373
+ except ValueError as exc:
374
+ raise HTTPException(400, str(exc)) from exc
375
+ return job.to_json()
376
+
377
+ @api.get("/jobs", tags=["jobs"])
378
+ def list_jobs(doc_id: str | None = None):
379
+ return [j.to_json() for j in jobs.list(doc_id)]
380
+
381
+ @api.get("/jobs/{job_id}", tags=["jobs"])
382
+ def get_job(job_id: str):
383
+ job = jobs.get(job_id)
384
+ if not job:
385
+ raise HTTPException(404, "no such job")
386
+ return job.to_json()
387
+
388
+ @api.post("/jobs/{job_id}/cancel", tags=["jobs"])
389
+ def cancel_job(job_id: str):
390
+ job = jobs.cancel(job_id)
391
+ if not job:
392
+ raise HTTPException(404, "no such job")
393
+ return job.to_json()
394
+
395
+ # ----------------------------------------------------------------- compare
396
+ @api.post("/documents/{doc_id}/pages/{page}/compare", tags=["compare"])
397
+ def compare_page(doc_id: str, page: int, body: CompareBody):
398
+ doc = get_doc(doc_id)
399
+ def text_of(ref: TextRef) -> str:
400
+ # OCR is run on demand (and cached); LLM results must exist already.
401
+ text = services.page_text(doc, page, ref.source_id, run_ocr=True)
402
+ if text is None:
403
+ raise DocumentError(f"no LLM transcription for page {page + 1} yet - run one first")
404
+ return text
405
+
406
+ ref_text = text_of(body.reference)
407
+ hyp_text = text_of(body.hypothesis)
408
+ opts = compare.NormalizeOptions(body.ignore_case, body.ignore_punctuation)
409
+ return {
410
+ "reference": {"label": services.source_label(doc, body.reference.source_id), **body.reference.model_dump()},
411
+ "hypothesis": {"label": services.source_label(doc, body.hypothesis.source_id), **body.hypothesis.model_dump()},
412
+ "metrics": compare.score(ref_text, hyp_text, opts),
413
+ "diff": compare.word_diff(ref_text, hyp_text, opts) if body.diff else None,
414
+ }
415
+
416
+ @api.get("/documents/{doc_id}/compare", tags=["compare"])
417
+ def compare_document(doc_id: str, a: str = Query(..., description="reference source id"),
418
+ b: str = Query(..., description="candidate source id"),
419
+ ignore_case: bool = True, ignore_punctuation: bool = False):
420
+ """Score source ``b`` against source ``a`` on every page where both exist.
421
+
422
+ ``overall`` is micro-averaged (total edits / total reference chars), so
423
+ long pages weigh more than short ones - the honest whole-document number.
424
+ """
425
+ doc = get_doc(doc_id)
426
+ opts = compare.NormalizeOptions(ignore_case, ignore_punctuation)
427
+ rows, tot_cd, tot_rc, tot_wd, tot_rw = [], 0, 0, 0, 0
428
+ for n in doc.iter_pages():
429
+ ta, tb = services.page_text(doc, n, a), services.page_text(doc, n, b)
430
+ if ta is None or tb is None:
431
+ rows.append({"page": n, "metrics": None, "missing": [s for s, t in ((a, ta), (b, tb)) if t is None]})
432
+ continue
433
+ m = compare.score(ta, tb, opts)
434
+ tot_cd += m["char_distance"]; tot_rc += m["reference_chars"]
435
+ tot_wd += m["word_distance"]; tot_rw += m["reference_words"]
436
+ rows.append({"page": n, "metrics": m, "missing": []})
437
+ scored = [r for r in rows if r["metrics"]]
438
+ overall = None
439
+ if scored:
440
+ overall = {
441
+ "pages_scored": len(scored),
442
+ "cer": round(tot_cd / tot_rc, 4) if tot_rc else None,
443
+ "wer": round(tot_wd / tot_rw, 4) if tot_rw else None,
444
+ "worst_page": max(scored, key=lambda r: r["metrics"]["cer"])["page"],
445
+ "pages_over_10pct": sum(r["metrics"]["cer"] > 0.10 for r in scored),
446
+ }
447
+ return {"a": {"id": a, "label": services.source_label(doc, a)},
448
+ "b": {"id": b, "label": services.source_label(doc, b)},
449
+ "overall": overall, "pages": rows}
450
+
451
+ @api.get("/documents/{doc_id}/report", tags=["compare"])
452
+ def report(doc_id: str, ignore_case: bool = True, ignore_punctuation: bool = False):
453
+ """Per-page overview against the most recent LLM transcription of each page."""
454
+ doc = get_doc(doc_id)
455
+ opts = compare.NormalizeOptions(ignore_case, ignore_punctuation)
456
+ rows = []
457
+ for n in doc.iter_pages():
458
+ native = doc.native_text(n).text
459
+ ocr = doc.cached_ocr_text(n)
460
+ llm = doc.list_llm_results(n)
461
+ row = {"page": n, "native_chars": len(native.strip()),
462
+ "ocr_chars": len(ocr.text.strip()) if ocr else None, "llm_runs": len(llm),
463
+ "llm_model": f"{llm[0]['provider']} / {llm[0]['model']}" if llm else None,
464
+ "native_vs_llm": None, "ocr_vs_llm": None, "native_vs_ocr": None}
465
+ if llm:
466
+ if native.strip():
467
+ row["native_vs_llm"] = compare.score(llm[0]["text"], native, opts)
468
+ if ocr:
469
+ row["ocr_vs_llm"] = compare.score(llm[0]["text"], ocr.text, opts)
470
+ if ocr and native.strip():
471
+ row["native_vs_ocr"] = compare.score(native, ocr.text, opts)
472
+ rows.append(row)
473
+ return {"document": doc.meta.__dict__, "pages": rows}
474
+
475
+ # ------------------------------------------------------------------ search
476
+ def _search_doc(doc: OpenDocument, q: str, wanted: set[str], limit_per_page: int, boxes: bool = True):
477
+ pages_out, total, ocr_missing = [], 0, 0
478
+ for n in doc.iter_pages():
479
+ hits = []
480
+ if "native" in wanted:
481
+ layer = doc.native_text(n)
482
+ if count := search.count_matches(layer.text, q):
483
+ hits.append({"source": "native", "label": "Native text", "count": count,
484
+ "boxes": search.find_boxes(layer.words, q) if boxes else [],
485
+ "snippets": search.find_snippets(layer.text, q, limit=limit_per_page)})
486
+ if "ocr" in wanted:
487
+ layer = doc.cached_ocr_text(n)
488
+ if layer is None:
489
+ ocr_missing += 1
490
+ elif count := search.count_matches(layer.text, q):
491
+ hits.append({"source": "ocr", "label": "Tesseract OCR", "count": count,
492
+ "boxes": search.find_boxes(layer.words, q) if boxes else [],
493
+ "snippets": search.find_snippets(layer.text, q, limit=limit_per_page)})
494
+ if "llm" in wanted:
495
+ for r in doc.list_llm_results(n):
496
+ if count := search.count_matches(r["text"], q):
497
+ hits.append({"source": "llm", "key": r["key"], "label": f"LLM: {r['provider']} / {r['model']}",
498
+ "count": count, "boxes": [],
499
+ "snippets": search.find_snippets(r["text"], q, limit=limit_per_page)})
500
+ if hits:
501
+ total += sum(h["count"] for h in hits)
502
+ pages_out.append({"page": n, "hits": hits})
503
+ return pages_out, total, ocr_missing
504
+
505
+ @api.get("/documents/{doc_id}/search", tags=["search"])
506
+ def search_document(doc_id: str, q: str = Query(..., min_length=1), sources: str = "native,ocr,llm",
507
+ limit_per_page: int = Query(10, ge=1, le=100)):
508
+ """Search every page. OCR is only searched on pages already OCR'd (it's slow)."""
509
+ wanted = {s.strip() for s in sources.split(",") if s.strip()}
510
+ pages_out, total, missing = _search_doc(get_doc(doc_id), q, wanted, limit_per_page)
511
+ return {"query": q, "total": total, "pages": pages_out, "pages_without_ocr": missing}
512
+
513
+ @api.get("/search", tags=["search"])
514
+ def search_library(q: str = Query(..., min_length=1), sources: str = "native,ocr,llm",
515
+ max_documents: int = Query(50, ge=1, le=500)):
516
+ """Search all documents in the library (snippets only, no boxes)."""
517
+ wanted = {s.strip() for s in sources.split(",") if s.strip()}
518
+ results, total = [], 0
519
+ for meta in store.list()[:max_documents]:
520
+ pages_out, doc_total, _ = _search_doc(store.get(meta.id), q, wanted, 3, boxes=False)
521
+ if pages_out:
522
+ total += doc_total
523
+ results.append({"document": meta.__dict__, "total": doc_total, "pages": pages_out[:25]})
524
+ return {"query": q, "total": total, "documents": results}
525
+
526
+ # ------------------------------------------------------------------ export
527
+ @api.get("/documents/{doc_id}/export", tags=["text"])
528
+ def export(doc_id: str, source: str = "llm", fmt: Literal["txt", "md", "json", "jsonl"] = "txt",
529
+ key: str | None = None):
530
+ """Download the whole document's text from one source.
531
+
532
+ ``source`` is ``native``, ``ocr``, ``llm`` (latest per page) or ``llm:<key>``.
533
+ ``jsonl`` writes one JSON object per page - handy for RAG / ingestion pipelines.
534
+ Pages without a result for that source are empty (nothing is run implicitly).
535
+ """
536
+ doc = get_doc(doc_id)
537
+ if key and source == "llm":
538
+ source = f"llm:{key}"
539
+ texts = [services.page_text(doc, n, source) for n in doc.iter_pages()]
540
+ stem, tag = _safe_stem(doc.meta.filename), source.split(":")[0]
541
+ disp = lambda ext: {"Content-Disposition": f'attachment; filename="{stem}.{tag}.{ext}"'} # noqa: E731
542
+ label = services.source_label(doc, source)
543
+ if fmt == "json":
544
+ return JSONResponse({"document": doc.meta.__dict__, "source": source, "source_label": label,
545
+ "pages": [{"page": i + 1, "text": t, "extracted": t is not None}
546
+ for i, t in enumerate(texts)]}, headers=disp("json"))
547
+ if fmt == "jsonl":
548
+ lines = (json.dumps({"document_id": doc.meta.id, "filename": doc.meta.filename, "page": i + 1,
549
+ "source": source, "text": t or ""}, ensure_ascii=False)
550
+ for i, t in enumerate(texts))
551
+ return PlainTextResponse("\n".join(lines) + "\n", media_type="application/x-ndjson", headers=disp("jsonl"))
552
+ if fmt == "md":
553
+ body = f"# {doc.meta.filename}\n\n_Source: {label}_\n" + "".join(
554
+ f"\n\n## Page {i + 1}\n\n{(t or '_(not extracted)_').strip()}" for i, t in enumerate(texts))
555
+ return PlainTextResponse(body + "\n", media_type="text/markdown", headers=disp("md"))
556
+ body = "".join(f"\n\n===== Page {i + 1} =====\n\n{(t or '').strip()}" for i, t in enumerate(texts)).lstrip()
557
+ return PlainTextResponse(body, headers=disp("txt"))
558
+
559
+ return api
560
+
561
+
562
+ def create_app(settings: Settings | None = None) -> FastAPI:
563
+ settings = settings or get_settings()
564
+ store = DocumentStore(settings.documents_dir)
565
+ providers = build_providers(settings)
566
+ services = Services(settings, providers)
567
+ jobs = JobManager(store, services)
568
+ workspaces = WorkspaceStore(settings.workspaces_dir, store)
569
+
570
+ app = FastAPI(title="pyocr-toolkit", version=__version__,
571
+ description="Inspect and compare PDF/image text extraction: native text, Tesseract OCR and LLMs.")
572
+ app.state.settings = settings
573
+ app.state.store = store
574
+ app.state.providers = providers
575
+ app.state.services = services
576
+ app.state.jobs = jobs
577
+ app.state.workspaces = workspaces
578
+
579
+ @app.exception_handler(DocumentError)
580
+ async def _doc_error(request: Request, exc: DocumentError):
581
+ status = 503 if isinstance(exc, OCRUnavailableError) else 404 if str(exc).startswith("unknown ") else 400
582
+ if not request.url.path.startswith("/api"):
583
+ from .web import render_error
584
+ return render_error(request, status, str(exc))
585
+ return JSONResponse({"detail": str(exc)}, status_code=status)
586
+
587
+ @app.exception_handler(ProviderError)
588
+ async def _provider_error(_req, exc: ProviderError):
589
+ return JSONResponse({"detail": str(exc)}, status_code=502)
590
+
591
+ app.include_router(build_api(settings, store, services, jobs, workspaces))
592
+ from .web import build_web
593
+
594
+ app.include_router(build_web(settings, store, services, jobs, workspaces))
595
+ app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
596
+ return app
597
+
598
+
599
+ def __getattr__(name: str):
600
+ # ``uvicorn pyocr_toolkit.api:app`` support without building the app at import time.
601
+ if name == "app":
602
+ return create_app()
603
+ raise AttributeError(name)