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
pyocr_toolkit/cli.py ADDED
@@ -0,0 +1,315 @@
1
+ """Command line interface.
2
+
3
+ pyocr serve [--open] start the web app on http://127.0.0.1:8000
4
+ pyocr init write a .env template to the current directory
5
+ pyocr doctor check Tesseract, providers and the data directory
6
+ pyocr providers list LLM providers and whether they are configured
7
+ pyocr extract FILE --engine llm -p anthropic --pages 1-3 --format jsonl -o out.jsonl
8
+ pyocr compare FILE -p openai per-page OCR/native error rate against an LLM
9
+ pyocr import a.pdf b.pdf scans.zip [--workspace NAME]
10
+ add files (zips unpacked, folders walked) to the library as one workspace
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import asyncio
17
+ import json
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ from . import __version__
24
+ from .config import get_settings
25
+
26
+ ENV_TEMPLATE = Path(__file__).parent / "env.example"
27
+
28
+
29
+ # ---------------------------------------------------------------- helpers
30
+ def _services():
31
+ from .llm import build_providers
32
+ from .service import Services
33
+
34
+ settings = get_settings()
35
+ return settings, Services(settings, build_providers(settings))
36
+
37
+
38
+ def _write_output(text: str, out: Path | None) -> None:
39
+ if out:
40
+ out.write_text(text, encoding="utf-8")
41
+ print(f"wrote {out}", file=sys.stderr)
42
+ else:
43
+ sys.stdout.write(text if text.endswith("\n") else text + "\n")
44
+
45
+
46
+ # ---------------------------------------------------------------- commands
47
+ def cmd_serve(args: argparse.Namespace) -> int:
48
+ import threading
49
+ import webbrowser
50
+
51
+ import uvicorn
52
+
53
+ from .api import create_app
54
+
55
+ url = f"http://{'127.0.0.1' if args.host in ('0.0.0.0', '::') else args.host}:{args.port}"
56
+ print(f"pyocr-toolkit {__version__} → {url}", file=sys.stderr)
57
+ if args.open:
58
+ threading.Timer(1.2, lambda: webbrowser.open(url)).start()
59
+ uvicorn.run(create_app(), host=args.host, port=args.port, log_level=args.log_level)
60
+ return 0
61
+
62
+
63
+ def cmd_init(args: argparse.Namespace) -> int:
64
+ target = Path(args.path)
65
+ if target.exists() and not args.force:
66
+ print(f"{target} already exists (use --force to overwrite)", file=sys.stderr)
67
+ return 1
68
+ shutil.copyfile(ENV_TEMPLATE, target)
69
+ print(f"wrote {target}: fill in the API keys you have, then run `pyocr serve`.")
70
+ return 0
71
+
72
+
73
+ def cmd_providers(_args: argparse.Namespace) -> int:
74
+ _, services = _services()
75
+ for p in services.providers.values():
76
+ status = "ready" if p.configured else "missing " + ", ".join(p.missing_settings())
77
+ print(f"{p.id:20} {p.default_model or '-':28} {status}")
78
+ return 0
79
+
80
+
81
+ def cmd_doctor(_args: argparse.Namespace) -> int:
82
+ settings, services = _services()
83
+ ok = True
84
+ print(f"pyocr-toolkit {__version__} (Python {sys.version.split()[0]})")
85
+ import pymupdf
86
+
87
+ print(f" PyMuPDF {pymupdf.VersionBind}")
88
+ tess = shutil.which("tesseract")
89
+ if tess:
90
+ out = subprocess.run([tess, "--list-langs"], capture_output=True, text=True).stdout
91
+ langs = [ln.strip() for ln in out.splitlines()[1:] if ln.strip()] # first line is a header
92
+ want = settings.tesseract_language.split("+")
93
+ missing = [lang for lang in want if lang not in langs]
94
+ print(f" Tesseract {tess} languages: {', '.join(langs) or '?'}")
95
+ if missing:
96
+ ok = False
97
+ print(f" ✗ language pack(s) missing for TESSERACT_LANGUAGE={settings.tesseract_language}: {', '.join(missing)}")
98
+ else:
99
+ print(" ✗ Tesseract not found: OCR is disabled (apt install tesseract-ocr / brew install tesseract)")
100
+ data = settings.data_dir.resolve()
101
+ try:
102
+ data.mkdir(parents=True, exist_ok=True)
103
+ probe = data / ".write-test"
104
+ probe.write_text("ok")
105
+ probe.unlink()
106
+ print(f" Data dir {data} (writable)")
107
+ except OSError as exc:
108
+ ok = False
109
+ print(f" ✗ Data dir {data} is not writable: {exc}")
110
+ env = Path(".env")
111
+ print(f" .env {'found' if env.exists() else 'not found (run `pyocr init`)'} in {Path.cwd()}")
112
+ ready = [p for p in services.providers.values() if p.configured]
113
+ print(f" LLM providers {len(ready)} of {len(services.providers)} configured")
114
+ for p in services.providers.values():
115
+ mark = "✓" if p.configured else "·"
116
+ extra = "" if p.configured else f" (set {', '.join(p.missing_settings())})"
117
+ print(f" {mark} {p.label}{extra}")
118
+ if not ready:
119
+ print(" Native text and OCR work without any provider; add a key to compare against LLMs.")
120
+ return 0 if ok else 1
121
+
122
+
123
+ def cmd_import(args: argparse.Namespace) -> int:
124
+ from .documents import SUPPORTED_EXTENSIONS, DocumentError, DocumentStore
125
+ from .workspaces import ARCHIVE_EXTENSIONS, WorkspaceStore, ingest, is_archive, suggest_names
126
+
127
+ settings = get_settings()
128
+ store = DocumentStore(settings.documents_dir)
129
+ spaces = WorkspaceStore(settings.workspaces_dir, store)
130
+ paths: list[Path] = []
131
+ for path in args.files:
132
+ if path.is_dir():
133
+ wanted = SUPPORTED_EXTENSIONS | ARCHIVE_EXTENSIONS
134
+ paths += sorted(p for p in path.rglob("*") if p.is_file() and p.suffix.lower() in wanted
135
+ and not any(part.startswith(".") for part in p.relative_to(path).parts))
136
+ elif path.is_file():
137
+ paths.append(path)
138
+ else:
139
+ raise FileNotFoundError(f"no such file or folder: {path}")
140
+ if not paths:
141
+ raise ValueError("nothing to import: no supported files found")
142
+
143
+ grouped = not args.no_workspace and (args.workspace or len(paths) > 1 or any(is_archive(p.name) for p in paths))
144
+ try:
145
+ if grouped:
146
+ name = args.workspace or suggest_names([p.name for p in args.files], taken=[w.name for w in spaces.list()],
147
+ count=1)[0]
148
+ ws = spaces.create(name)
149
+ result = ingest(store, ((p.name, p.read_bytes()) for p in paths), max_bytes=settings.max_upload_mb * 1024 * 1024)
150
+ if grouped:
151
+ ws = spaces.add_documents(ws.id, [m.id for m in result.documents])
152
+ except DocumentError as exc:
153
+ print(f"error: {exc}", file=sys.stderr)
154
+ return 2
155
+ for meta in result.documents:
156
+ print(f" ✓ {meta.filename} ({meta.page_count} page{'s' if meta.page_count != 1 else ''}) {meta.id}")
157
+ for item in result.skipped:
158
+ print(f" · skipped {item['name']}: {item['reason']}")
159
+ where = f"workspace '{ws.name}' ({ws.id})" if grouped else "the library"
160
+ print(f"Added {len(result.documents)} document(s) to {where}.", file=sys.stderr)
161
+ return 0 if result.documents else 1
162
+
163
+
164
+ def _load_document(path: Path):
165
+ from .documents import DocumentStore
166
+
167
+ settings = get_settings()
168
+ store = DocumentStore(settings.documents_dir)
169
+ meta = store.add(path.name, path.read_bytes())
170
+ return store.get(meta.id)
171
+
172
+
173
+ async def _extract(args: argparse.Namespace) -> int:
174
+ from .service import LLMSpec, parse_pages
175
+
176
+ settings, services = _services()
177
+ doc = _load_document(args.file)
178
+ pages = parse_pages(args.pages, doc.meta.page_count)
179
+ texts: dict[int, str] = {}
180
+ if args.engine == "native":
181
+ texts = {n: doc.native_text(n).text for n in pages}
182
+ elif args.engine == "ocr":
183
+ for n in pages:
184
+ texts[n] = (await asyncio.to_thread(services.run_ocr_page, doc, n)).text
185
+ print(f" OCR page {n + 1}/{doc.meta.page_count}", file=sys.stderr)
186
+ else:
187
+ spec = LLMSpec(args.provider, args.model, args.mode)
188
+ provider, model, _ = services.resolve_spec(spec)
189
+ if not provider.configured:
190
+ print(f"{provider.label} is not configured: set {', '.join(provider.missing_settings())}", file=sys.stderr)
191
+ return 2
192
+
193
+ async def one(n: int):
194
+ res = await services.run_llm_page(doc, n, spec)
195
+ note = "cached" if res["cached"] else f"{res['latency_ms'] / 1000:.1f}s"
196
+ print(f" LLM page {n + 1}: {note}" + "".join(f" ⚠ {w}" for w in res["warnings"]), file=sys.stderr)
197
+ texts[n] = res["text"]
198
+
199
+ results = await asyncio.gather(*(one(n) for n in pages), return_exceptions=True)
200
+ for n, r in zip(pages, results):
201
+ if isinstance(r, Exception):
202
+ print(f" page {n + 1} failed: {r}", file=sys.stderr)
203
+
204
+ ordered = [(n, texts.get(n, "")) for n in pages]
205
+ source = args.engine if args.engine != "llm" else f"llm:{args.provider}"
206
+ if args.format == "jsonl":
207
+ out = "".join(json.dumps({"document_id": doc.meta.id, "filename": doc.meta.filename, "page": n + 1,
208
+ "source": source, "text": t}, ensure_ascii=False) + "\n" for n, t in ordered)
209
+ elif args.format == "json":
210
+ out = json.dumps({"document": doc.meta.__dict__, "source": source,
211
+ "pages": [{"page": n + 1, "text": t} for n, t in ordered]}, ensure_ascii=False, indent=1)
212
+ elif args.format == "md":
213
+ out = f"# {doc.meta.filename}\n" + "".join(f"\n## Page {n + 1}\n\n{t.strip()}\n" for n, t in ordered)
214
+ else:
215
+ out = "\n\n".join(f"===== Page {n + 1} =====\n\n{t.strip()}" for n, t in ordered)
216
+ _write_output(out, args.output)
217
+ print(f"document {doc.meta.id} is in the library; inspect it with `pyocr serve`", file=sys.stderr)
218
+ return 0
219
+
220
+
221
+ async def _compare(args: argparse.Namespace) -> int:
222
+ from . import compare
223
+ from .service import LLMSpec, parse_pages
224
+
225
+ settings, services = _services()
226
+ doc = _load_document(args.file)
227
+ spec = LLMSpec(args.provider, args.model, "verbatim")
228
+ provider, _, _ = services.resolve_spec(spec)
229
+ if not provider.configured:
230
+ print(f"{provider.label} is not configured: set {', '.join(provider.missing_settings())}", file=sys.stderr)
231
+ return 2
232
+ pages = parse_pages(args.pages, doc.meta.page_count)
233
+ llm = await asyncio.gather(*(services.run_llm_page(doc, n, spec) for n in pages))
234
+ opts = compare.NormalizeOptions(ignore_case=True)
235
+ has_tess = shutil.which("tesseract") is not None
236
+ print(f"{'page':>5} {'OCR CER':>8} {'OCR WER':>8} {'native CER':>10}")
237
+ for n, res in zip(pages, llm):
238
+ native = doc.native_text(n).text
239
+ ocr_cer = ocr_wer = "–"
240
+ if has_tess:
241
+ s = compare.score(res["text"], services.run_ocr_page(doc, n).text, opts)
242
+ ocr_cer, ocr_wer = f"{s['cer']:.1%}", f"{s['wer']:.1%}"
243
+ nat = f"{compare.score(res['text'], native, opts)['cer']:.1%}" if native.strip() else "no text"
244
+ print(f"{n + 1:>5} {ocr_cer:>8} {ocr_wer:>8} {nat:>10}")
245
+ print(f"\ndocument {doc.meta.id}: open http://127.0.0.1:8000/documents/{doc.meta.id}/compare for diffs",
246
+ file=sys.stderr)
247
+ return 0
248
+
249
+
250
+ # ---------------------------------------------------------------- parser
251
+ def build_parser() -> argparse.ArgumentParser:
252
+ parser = argparse.ArgumentParser(prog="pyocr", description=__doc__,
253
+ formatter_class=argparse.RawDescriptionHelpFormatter)
254
+ parser.add_argument("--version", action="version", version=f"pyocr-toolkit {__version__}")
255
+ sub = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
256
+
257
+ s = sub.add_parser("serve", help="run the web app")
258
+ s.add_argument("--host", default="127.0.0.1", help="use 0.0.0.0 to allow other machines (no auth!)")
259
+ s.add_argument("--port", type=int, default=8000)
260
+ s.add_argument("--open", action="store_true", help="open the browser")
261
+ s.add_argument("--log-level", default="info")
262
+ s.set_defaults(func=cmd_serve)
263
+
264
+ i = sub.add_parser("init", help="write a .env template here")
265
+ i.add_argument("--path", default=".env")
266
+ i.add_argument("--force", action="store_true")
267
+ i.set_defaults(func=cmd_init)
268
+
269
+ sub.add_parser("doctor", help="check the installation").set_defaults(func=cmd_doctor)
270
+ sub.add_parser("providers", help="list LLM providers").set_defaults(func=cmd_providers)
271
+
272
+ e = sub.add_parser("extract", help="extract text from a PDF/image (whole document or pages)")
273
+ e.add_argument("file", type=Path)
274
+ e.add_argument("--engine", choices=["native", "ocr", "llm"], default="llm")
275
+ e.add_argument("-p", "--provider", default="anthropic", help="for --engine llm")
276
+ e.add_argument("-m", "--model", default=None)
277
+ e.add_argument("--mode", default="verbatim", choices=["verbatim", "markdown"], help="LLM prompt")
278
+ e.add_argument("--pages", default=None, help="1-based ranges, e.g. 1-3,7 (default: all)")
279
+ e.add_argument("--format", choices=["txt", "md", "json", "jsonl"], default="txt")
280
+ e.add_argument("-o", "--output", type=Path, default=None, help="file to write (default: stdout)")
281
+ e.set_defaults(func=lambda a: asyncio.run(_extract(a)))
282
+
283
+ m = sub.add_parser("import", help="add files, folders or .zip archives to the library as one workspace")
284
+ m.add_argument("files", type=Path, nargs="+")
285
+ m.add_argument("-w", "--workspace", default=None, help="workspace name (default: a suggested one)")
286
+ m.add_argument("--no-workspace", action="store_true", help="add to the library without grouping")
287
+ m.set_defaults(func=cmd_import)
288
+
289
+ c = sub.add_parser("compare", help="score Tesseract / native text against an LLM transcription")
290
+ c.add_argument("file", type=Path)
291
+ c.add_argument("-p", "--provider", default="anthropic")
292
+ c.add_argument("-m", "--model", default=None)
293
+ c.add_argument("--pages", default=None)
294
+ c.set_defaults(func=lambda a: asyncio.run(_compare(a)))
295
+ return parser
296
+
297
+
298
+ def main(argv: list[str] | None = None) -> None:
299
+ # Windows consoles may not be UTF-8; never crash on a ✓ or an OCR'd glyph.
300
+ for stream in (sys.stdout, sys.stderr):
301
+ if hasattr(stream, "reconfigure"):
302
+ try:
303
+ stream.reconfigure(errors="replace")
304
+ except (ValueError, OSError):
305
+ pass
306
+ args = build_parser().parse_args(argv)
307
+ try:
308
+ sys.exit(args.func(args))
309
+ except (ValueError, FileNotFoundError) as exc:
310
+ print(f"error: {exc}", file=sys.stderr)
311
+ sys.exit(2)
312
+
313
+
314
+ if __name__ == "__main__":
315
+ main()
@@ -0,0 +1,142 @@
1
+ """Text comparison: error rates and a word-level diff.
2
+
3
+ How the numbers are defined
4
+ ---------------------------
5
+ We compare a *hypothesis* (the text we are judging, e.g. Tesseract output)
6
+ against a *reference* (the text we trust more, e.g. an LLM transcription or
7
+ the PDF's own text layer).
8
+
9
+ * **Edit distance** (Levenshtein) is the minimum number of single-item
10
+ insertions, deletions and substitutions that turn one sequence into the
11
+ other.
12
+ * **CER** (character error rate) = char edit distance / reference length.
13
+ * **WER** (word error rate) = word edit distance / reference word count.
14
+
15
+ Both are 0.0 for a perfect match and can exceed 1.0 when the hypothesis has
16
+ lots of extra text. ``accuracy`` is ``max(0, 1 - CER)``, a friendlier number.
17
+
18
+ Whitespace is collapsed before scoring because OCR engines and LLMs disagree
19
+ wildly on line breaks and spacing, which says nothing about whether the
20
+ characters were *read* correctly. Optional flags also ignore case and
21
+ punctuation.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import re
27
+ import string
28
+ import unicodedata
29
+ from dataclasses import dataclass
30
+
31
+ from rapidfuzz.distance import Levenshtein
32
+
33
+ _PUNCT_TABLE = str.maketrans("", "", string.punctuation + "“”‘’«»–—…•·")
34
+ _TOKEN_RE = re.compile(r"\n|[^\S\n]+|[^\s]+")
35
+
36
+
37
+ @dataclass
38
+ class NormalizeOptions:
39
+ ignore_case: bool = False
40
+ ignore_punctuation: bool = False
41
+
42
+
43
+ def normalize(text: str, opts: NormalizeOptions | None = None) -> str:
44
+ opts = opts or NormalizeOptions()
45
+ # NFKC folds ligatures (fi -> fi) and full-width forms, which PDFs love.
46
+ text = unicodedata.normalize("NFKC", text)
47
+ # Undo hyphenation at line ends: "recog-\nnition" -> "recognition".
48
+ text = re.sub(r"(\w)-\n(\w)", r"\1\2", text)
49
+ if opts.ignore_case:
50
+ text = text.casefold()
51
+ if opts.ignore_punctuation:
52
+ text = text.translate(_PUNCT_TABLE)
53
+ return " ".join(text.split())
54
+
55
+
56
+ def score(reference: str, hypothesis: str, opts: NormalizeOptions | None = None) -> dict:
57
+ ref = normalize(reference, opts)
58
+ hyp = normalize(hypothesis, opts)
59
+ ref_words, hyp_words = ref.split(), hyp.split()
60
+ char_dist = Levenshtein.distance(ref, hyp)
61
+ word_dist = Levenshtein.distance(ref_words, hyp_words)
62
+ cer = char_dist / len(ref) if ref else (0.0 if not hyp else 1.0)
63
+ wer = word_dist / len(ref_words) if ref_words else (0.0 if not hyp_words else 1.0)
64
+ return {
65
+ "cer": round(cer, 4),
66
+ "wer": round(wer, 4),
67
+ "accuracy": round(max(0.0, 1.0 - cer), 4),
68
+ "char_distance": char_dist,
69
+ "word_distance": word_dist,
70
+ "reference_chars": len(ref),
71
+ "hypothesis_chars": len(hyp),
72
+ "reference_words": len(ref_words),
73
+ "hypothesis_words": len(hyp_words),
74
+ }
75
+
76
+
77
+ def _tokens(text: str) -> list[str]:
78
+ """Split into words, keeping newlines as their own tokens (spaces dropped)."""
79
+ text = unicodedata.normalize("NFKC", text)
80
+ text = re.sub(r"\n{3,}", "\n\n", text.strip())
81
+ return [t for t in _TOKEN_RE.findall(text) if t == "\n" or not t.isspace()]
82
+
83
+
84
+ def _key(token: str, opts: NormalizeOptions) -> str:
85
+ if opts.ignore_case:
86
+ token = token.casefold()
87
+ if opts.ignore_punctuation:
88
+ token = token.translate(_PUNCT_TABLE)
89
+ return token
90
+
91
+
92
+ def word_diff(reference: str, hypothesis: str, opts: NormalizeOptions | None = None) -> list[dict]:
93
+ """Word-level diff as a list of segments for display.
94
+
95
+ Each segment is ``{"op": "equal"|"delete"|"insert"|"replace", "ref": str, "hyp": str}``.
96
+ ``delete`` = present in the reference but missed by the hypothesis;
97
+ ``insert`` = extra text in the hypothesis.
98
+ Line breaks are ignored when aligning (so a reflowed paragraph still
99
+ matches) but kept in the output text so the diff stays readable.
100
+ """
101
+ opts = opts or NormalizeOptions()
102
+ ref_tokens, hyp_tokens = _tokens(reference), _tokens(hypothesis)
103
+ ref_words = [i for i, t in enumerate(ref_tokens) if t != "\n"]
104
+ hyp_words = [i for i, t in enumerate(hyp_tokens) if t != "\n"]
105
+ ref_keys = [_key(ref_tokens[i], opts) for i in ref_words]
106
+ hyp_keys = [_key(hyp_tokens[i], opts) for i in hyp_words]
107
+
108
+ def join(tokens: list[str], idx: list[int], start: int, end: int) -> str:
109
+ if start >= end:
110
+ return ""
111
+ # include newlines between the selected words and the ones just
112
+ # before the first word, so line structure survives segment borders
113
+ lo = idx[start - 1] + 1 if start > 0 else 0
114
+ hi = idx[end - 1]
115
+ out = []
116
+ for tok in tokens[lo : hi + 1]:
117
+ if tok == "\n":
118
+ out.append("\n")
119
+ else:
120
+ if out and out[-1] != "\n":
121
+ out.append(" ")
122
+ out.append(tok)
123
+ return "".join(out)
124
+
125
+ segments: list[dict] = []
126
+ for op in Levenshtein.opcodes(ref_keys, hyp_keys):
127
+ segments.append({
128
+ "op": op.tag,
129
+ "ref": join(ref_tokens, ref_words, op.src_start, op.src_end),
130
+ "hyp": join(hyp_tokens, hyp_words, op.dest_start, op.dest_end),
131
+ })
132
+ # Merge neighbouring segments of the same kind to keep the payload small.
133
+ merged: list[dict] = []
134
+ for seg in segments:
135
+ if merged and merged[-1]["op"] == seg["op"]:
136
+ for side in ("ref", "hyp"):
137
+ if seg[side]:
138
+ sep = "" if not merged[-1][side] or seg[side].startswith("\n") else " "
139
+ merged[-1][side] += sep + seg[side]
140
+ else:
141
+ merged.append(dict(seg))
142
+ return merged
@@ -0,0 +1,86 @@
1
+ """Runtime configuration.
2
+
3
+ Every setting can be supplied through environment variables (or a ``.env``
4
+ file in the working directory). Provider credentials are *only* read on the
5
+ server side; the browser never sees an API key.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from functools import lru_cache
11
+ from pathlib import Path
12
+
13
+ from pydantic_settings import BaseSettings, SettingsConfigDict
14
+
15
+
16
+ class Settings(BaseSettings):
17
+ model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
18
+
19
+ # --- storage / rendering -------------------------------------------------
20
+ data_dir: Path = Path("data")
21
+ max_upload_mb: int = 200
22
+ # DPI used for the page preview shown in the browser.
23
+ preview_dpi: int = 110
24
+ # DPI used for the image sent to the LLM and for Tesseract OCR.
25
+ llm_dpi: int = 200
26
+ ocr_dpi: int = 300
27
+ # Longest edge (px) of the image sent to an LLM. Larger images get
28
+ # downscaled; most vision models resize internally anyway, so sending
29
+ # a huge bitmap only costs upload time.
30
+ llm_max_edge_px: int = 2400
31
+ tesseract_language: str = "eng"
32
+ # How many LLM calls may run at once when transcribing many pages.
33
+ llm_concurrency: int = 4
34
+ llm_timeout_s: float = 300.0
35
+ # Rupees per US dollar, used to show LLM costs in ₹ next to the USD list
36
+ # prices from the model catalog. Not fetched live (no outbound calls besides
37
+ # the chosen provider); ~92.5 on 2026-11-26. Set it to today's rate.
38
+ usd_inr_rate: float = 92.5
39
+
40
+ # --- OpenAI --------------------------------------------------------------
41
+ openai_api_key: str | None = None
42
+ openai_model: str = "gpt-6.2-sol"
43
+ openai_base_url: str | None = None
44
+
45
+ # --- Azure OpenAI --------------------------------------------------------
46
+ azure_openai_api_key: str | None = None
47
+ azure_openai_endpoint: str | None = None
48
+ azure_openai_api_version: str = "2024-10-21"
49
+ azure_openai_deployment: str | None = None
50
+
51
+ # --- Anthropic (Claude API) ----------------------------------------------
52
+ anthropic_api_key: str | None = None
53
+ anthropic_model: str = "claude-opus-5-5"
54
+ # Effort controls how much the model thinks before answering
55
+ # (low | medium | high | xhigh | max). Transcription is mostly perception,
56
+ # so "medium" is a good balance; raise it for dense/handwritten pages.
57
+ anthropic_effort: str = "medium"
58
+
59
+ # --- Claude on Microsoft Foundry (Azure) ---------------------------------
60
+ anthropic_foundry_api_key: str | None = None
61
+ anthropic_foundry_resource: str | None = None
62
+ anthropic_foundry_base_url: str | None = None
63
+ anthropic_foundry_model: str = "claude-opus-5-5"
64
+
65
+ # --- Google Gemini -------------------------------------------------------
66
+ gemini_api_key: str | None = None
67
+ google_api_key: str | None = None
68
+ gemini_model: str = "gemini-3.8-flash"
69
+
70
+ # --- Any OpenAI-compatible server (Ollama, vLLM, LM Studio, OpenRouter) --
71
+ openai_compatible_base_url: str | None = None
72
+ openai_compatible_api_key: str | None = None
73
+ openai_compatible_model: str | None = None
74
+
75
+ @property
76
+ def documents_dir(self) -> Path:
77
+ return self.data_dir / "documents"
78
+
79
+ @property
80
+ def workspaces_dir(self) -> Path:
81
+ return self.data_dir / "workspaces"
82
+
83
+
84
+ @lru_cache
85
+ def get_settings() -> Settings:
86
+ return Settings()
@@ -0,0 +1,108 @@
1
+ """Provider credentials and settings saved from the web UI.
2
+
3
+ Environment variables and ``.env`` stay the primary way to configure providers, but
4
+ editing a file and restarting the server is a poor experience for a local tool. The
5
+ Providers page can therefore save values into ``<DATA_DIR>/credentials.json``; they are
6
+ applied on top of the environment at startup and immediately when saved.
7
+
8
+ Why a separate file in the data dir rather than rewriting ``.env``: the ``.env`` may be
9
+ shared or hand-edited (comments, ordering), the data dir is already per-user and
10
+ git-ignored, and keeping UI values separate makes "clear and fall back to the
11
+ environment" trivial. The file is created with owner-only permissions.
12
+
13
+ Secrets still never reach the browser: callers get set / missing / saved-here states,
14
+ plus the value only for settings that aren't secrets (model names, endpoints).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from .config import Settings
25
+ from .llm.base import Provider
26
+
27
+
28
+ def is_secret(name: str) -> bool:
29
+ return "KEY" in name or "SECRET" in name or "TOKEN" in name
30
+
31
+
32
+ class CredentialStore:
33
+ FILENAME = "credentials.json"
34
+
35
+ def __init__(self, settings: Settings, providers: dict[str, Provider]) -> None:
36
+ self.settings = settings
37
+ self.providers = providers
38
+ self.path = Path(settings.data_dir) / self.FILENAME
39
+ #: env var name -> provider id, for every setting a provider declares
40
+ self.allowed: dict[str, str] = {}
41
+ for p in providers.values():
42
+ for name, _required, _desc in p.env_vars:
43
+ if hasattr(settings, name.lower()):
44
+ self.allowed.setdefault(name, p.id)
45
+ # What the environment / .env / defaults gave us, so "clear" can restore it.
46
+ self._base: dict[str, Any] = {n: getattr(settings, n.lower()) for n in self.allowed}
47
+ self.saved: dict[str, str] = self._read()
48
+ for name, value in self.saved.items():
49
+ setattr(settings, name.lower(), value)
50
+
51
+ def _read(self) -> dict[str, str]:
52
+ try:
53
+ data = json.loads(self.path.read_text(encoding="utf-8"))
54
+ except (OSError, ValueError):
55
+ return {}
56
+ if not isinstance(data, dict):
57
+ return {}
58
+ return {k: v for k, v in data.items() if k in self.allowed and isinstance(v, str) and v}
59
+
60
+ def _write(self) -> None:
61
+ self.path.parent.mkdir(parents=True, exist_ok=True)
62
+ tmp = self.path.with_suffix(".tmp")
63
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
64
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
65
+ json.dump(self.saved, fh, indent=2, sort_keys=True)
66
+ os.replace(tmp, self.path)
67
+
68
+ def update(self, provider_id: str, values: dict[str, str | None], clear: list[str] | None = None) -> None:
69
+ """Save non-empty ``values`` and drop ``clear``-ed names (back to env/default).
70
+
71
+ Empty strings in ``values`` mean "leave unchanged", so a form can send every field
72
+ without re-typing secrets it doesn't show.
73
+ """
74
+ provider = self.providers.get(provider_id)
75
+ if provider is None:
76
+ raise ValueError(f"unknown provider '{provider_id}'")
77
+ own = {name for name, _r, _d in provider.env_vars if name in self.allowed}
78
+ for name in [*values, *(clear or [])]:
79
+ if name not in own:
80
+ raise ValueError(f"{name} is not a setting of {provider.label}")
81
+ for name in clear or []:
82
+ self.saved.pop(name, None)
83
+ setattr(self.settings, name.lower(), self._base[name])
84
+ for name, value in values.items():
85
+ value = (value or "").strip()
86
+ if not value:
87
+ continue
88
+ if any(c in value for c in "\r\n\0"):
89
+ raise ValueError(f"{name} must be a single line")
90
+ self.saved[name] = value
91
+ setattr(self.settings, name.lower(), value)
92
+ self._write()
93
+ provider.reset_client()
94
+
95
+ def status(self, provider: Provider) -> list[dict]:
96
+ """``env_status()`` plus where each value comes from and, for non-secrets, the value."""
97
+ out = []
98
+ for e in provider.env_status():
99
+ name = e["name"]
100
+ secret = is_secret(name)
101
+ value = getattr(self.settings, name.lower(), None)
102
+ e = {**e, "secret": secret, "saved": name in self.saved,
103
+ "editable": name in self.allowed,
104
+ "from_env": bool(self._base.get(name)) and self._base.get(name) != e.get("default")}
105
+ if not secret and isinstance(value, (str, int, float)):
106
+ e["value"] = value
107
+ out.append(e)
108
+ return out