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,538 @@
|
|
|
1
|
+
/* Shared helpers for every page. Loaded before the page-specific script. */
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
const $ = (sel, root = document) => root.querySelector(sel);
|
|
5
|
+
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
|
|
6
|
+
|
|
7
|
+
async function api(path, opts = {}) {
|
|
8
|
+
const res = await fetch(path, opts);
|
|
9
|
+
if (!res.ok) {
|
|
10
|
+
let detail = res.statusText;
|
|
11
|
+
try { const body = await res.json(); detail = body.detail || detail; } catch (_) { /* not json */ }
|
|
12
|
+
if (typeof detail !== "string") detail = JSON.stringify(detail);
|
|
13
|
+
throw new Error(detail);
|
|
14
|
+
}
|
|
15
|
+
if (res.status === 204) return null;
|
|
16
|
+
return res.json();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function postJSON(path, body) {
|
|
20
|
+
return api(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body ?? {}) });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
let _toastTimer;
|
|
24
|
+
function toast(msg, isError = false) {
|
|
25
|
+
const el = $("#toast");
|
|
26
|
+
if (!el) return alert(msg);
|
|
27
|
+
el.textContent = msg;
|
|
28
|
+
el.className = isError ? "error" : "";
|
|
29
|
+
el.hidden = false;
|
|
30
|
+
clearTimeout(_toastTimer);
|
|
31
|
+
_toastTimer = setTimeout(() => {
|
|
32
|
+
el.classList.add("leaving"); // fade out (styles.css), then hide
|
|
33
|
+
_toastTimer = setTimeout(() => { el.hidden = true; }, 180);
|
|
34
|
+
}, isError ? 8000 : 3000);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Replay a one-shot CSS animation class (e.g. "reveal") on an element. */
|
|
38
|
+
function replayAnimation(el, cls) {
|
|
39
|
+
el.classList.remove(cls);
|
|
40
|
+
void el.offsetWidth; // force a reflow so removing + re-adding restarts it
|
|
41
|
+
el.classList.add(cls);
|
|
42
|
+
el.addEventListener("animationend", () => el.classList.remove(cls), { once: true });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Show that `btn` is working: spinner + label, disabled. Returns a function that
|
|
47
|
+
* restores the button. Extra elements get `cls` toggled for the same duration
|
|
48
|
+
* (the workspace uses this for the page scan line and the shimmering text box).
|
|
49
|
+
*/
|
|
50
|
+
function setBusy(btn, label, extras = []) {
|
|
51
|
+
const prev = btn.innerHTML; // innerHTML, not textContent, so a button's icon survives
|
|
52
|
+
btn.disabled = true; btn.textContent = label; btn.classList.add("is-busy");
|
|
53
|
+
extras.forEach(([el, cls]) => el?.classList.add(cls));
|
|
54
|
+
return () => {
|
|
55
|
+
btn.disabled = false; btn.innerHTML = prev; btn.classList.remove("is-busy");
|
|
56
|
+
extras.forEach(([el, cls]) => el?.classList.remove(cls));
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Wrap an async handler so errors become toasts instead of silent failures. */
|
|
61
|
+
const guard = (fn) => async (...args) => { try { return await fn(...args); } catch (e) { toast(e.message, true); } };
|
|
62
|
+
|
|
63
|
+
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
|
64
|
+
const pct = (x) => (x == null ? "–" : (x * 100).toFixed(1) + "%");
|
|
65
|
+
const fmtInt = (n) => (n == null ? "–" : Number(n).toLocaleString());
|
|
66
|
+
function errorRateClass(rate) {
|
|
67
|
+
if (rate == null) return "";
|
|
68
|
+
return rate <= 0.02 ? "good" : rate <= 0.1 ? "warn" : "bad";
|
|
69
|
+
}
|
|
70
|
+
function queryRegex(q) {
|
|
71
|
+
const terms = (q || "").trim().split(/\s+/).filter(Boolean).map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
72
|
+
return terms.length ? new RegExp(terms.join("\\s+"), "gi") : null;
|
|
73
|
+
}
|
|
74
|
+
/** HTML for `text` with matches of `q` wrapped in <mark>. */
|
|
75
|
+
function highlight(text, q) {
|
|
76
|
+
const re = queryRegex(q);
|
|
77
|
+
if (!re || !text) return esc(text);
|
|
78
|
+
let html = "", last = 0;
|
|
79
|
+
for (const m of text.matchAll(re)) {
|
|
80
|
+
html += esc(text.slice(last, m.index)) + "<mark>" + esc(m[0]) + "</mark>";
|
|
81
|
+
last = m.index + m[0].length;
|
|
82
|
+
}
|
|
83
|
+
return html + esc(text.slice(last));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function copyText(text) {
|
|
87
|
+
try { await navigator.clipboard.writeText(text); toast("Copied to clipboard"); }
|
|
88
|
+
catch (_) { toast("Copy failed: the browser blocked clipboard access", true); }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ------------------------------------------------------------------ config
|
|
92
|
+
let _configPromise;
|
|
93
|
+
function getConfig() {
|
|
94
|
+
_configPromise ??= api("/api/config");
|
|
95
|
+
return _configPromise;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ------------------------------------------------------------------ uploads
|
|
99
|
+
const isZip = (file) => /\.zip$/i.test(file.name);
|
|
100
|
+
const fmtSize = (n) => (n < 1024 * 1024 ? `${Math.max(1, Math.round(n / 1024))} KB` : `${(n / 1024 / 1024).toFixed(1)} MB`);
|
|
101
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
102
|
+
|
|
103
|
+
/** Workspace name ideas from the server ("adjective-scientist", led by one taken from the file names). */
|
|
104
|
+
async function suggestNames(filenames = [], count = 4) {
|
|
105
|
+
return (await postJSON("/api/workspaces/suggest-names", { filenames, count })).names;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Upload files one request at a time (so each gets its own progress line) to
|
|
110
|
+
* /api/uploads, which unpacks zips. `onFile(i, status, text)` reports progress.
|
|
111
|
+
*/
|
|
112
|
+
async function sendBatch(files, workspaceId, onFile = () => {}) {
|
|
113
|
+
const documents = [], skipped = [];
|
|
114
|
+
for (const [i, file] of files.entries()) {
|
|
115
|
+
onFile(i, "run", isZip(file) ? "unpacking…" : "uploading…");
|
|
116
|
+
const fd = new FormData();
|
|
117
|
+
fd.append("files", file);
|
|
118
|
+
if (workspaceId) fd.append("workspace_id", workspaceId);
|
|
119
|
+
try {
|
|
120
|
+
const res = await api("/api/uploads", { method: "POST", body: fd });
|
|
121
|
+
documents.push(...res.documents);
|
|
122
|
+
skipped.push(...res.skipped);
|
|
123
|
+
const n = res.documents.length;
|
|
124
|
+
if (!n) onFile(i, "err", res.skipped[0]?.reason || "nothing to add");
|
|
125
|
+
else if (!isZip(file)) onFile(i, "ok", "added");
|
|
126
|
+
else onFile(i, "ok", plural(n, "document") + (res.skipped.length ? `, ${res.skipped.length} skipped` : ""));
|
|
127
|
+
} catch (e) {
|
|
128
|
+
skipped.push({ name: file.name, reason: e.message });
|
|
129
|
+
onFile(i, "err", e.message);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return { documents, skipped };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function skippedMessage(skipped) {
|
|
136
|
+
if (!skipped.length) return "";
|
|
137
|
+
const first = skipped.slice(0, 3).map((s) => `${s.name}: ${s.reason}`).join("; ");
|
|
138
|
+
return `Skipped ${plural(skipped.length, "file")} (${first}${skipped.length > 3 ? "; …" : ""})`;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function uploadFiles(files, { workspaceId } = {}) {
|
|
142
|
+
files = Array.from(files || []);
|
|
143
|
+
if (!files.length) return;
|
|
144
|
+
workspaceId ??= $("#ws-root")?.dataset.wsId; // on a workspace page, uploads go into it
|
|
145
|
+
if (workspaceId) {
|
|
146
|
+
toast(`Adding ${plural(files.length, "file")}…`);
|
|
147
|
+
const { documents, skipped } = await sendBatch(files, workspaceId);
|
|
148
|
+
if (skipped.length) { toast(skippedMessage(skipped), true); await new Promise((r) => setTimeout(r, 2500)); }
|
|
149
|
+
if (documents.length) location.href = `/workspaces/${workspaceId}`;
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (files.length > 1 || isZip(files[0])) return openUploadDialog(files);
|
|
153
|
+
|
|
154
|
+
const file = files[0];
|
|
155
|
+
toast(`Uploading ${file.name}…`);
|
|
156
|
+
const fd = new FormData();
|
|
157
|
+
fd.append("file", file);
|
|
158
|
+
try {
|
|
159
|
+
const doc = await api("/api/documents", { method: "POST", body: fd });
|
|
160
|
+
location.href = `/documents/${doc.id}`;
|
|
161
|
+
} catch (e) {
|
|
162
|
+
toast(`${file.name}: ${e.message}`, true);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Several files or a zip: ask which workspace they belong to (with name suggestions), then upload. */
|
|
167
|
+
async function openUploadDialog(files) {
|
|
168
|
+
const dlg = $("#upload-dialog");
|
|
169
|
+
if (!dlg?.showModal) { // very old browser: upload without a workspace
|
|
170
|
+
const { skipped } = await sendBatch(files, null);
|
|
171
|
+
if (skipped.length) toast(skippedMessage(skipped), true);
|
|
172
|
+
location.href = "/documents";
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const nameIn = $("#upload-ws-name"), chips = $("#upload-ws-suggest"), existing = $("#upload-ws-existing");
|
|
176
|
+
const okBtn = $("#upload-ok"), list = $("#upload-files");
|
|
177
|
+
const radios = $$("input[name=ws-mode]", dlg);
|
|
178
|
+
const mode = () => $("input[name=ws-mode]:checked", dlg).value;
|
|
179
|
+
const filenames = files.map((f) => f.name);
|
|
180
|
+
let done = null; // set once uploads finish: where "Continue" goes
|
|
181
|
+
|
|
182
|
+
const zips = files.filter(isZip).length;
|
|
183
|
+
const total = files.reduce((n, f) => n + f.size, 0);
|
|
184
|
+
$("#upload-summary").textContent = `${plural(files.length, "file")} · ${fmtSize(total)}` +
|
|
185
|
+
(zips ? ` · ${zips === 1 ? "the zip" : `${zips} zips`} will be unpacked` : "");
|
|
186
|
+
list.innerHTML = files.map((f) => `<li><span title="${esc(f.name)}">${esc(f.name)}</span><span>${esc(fmtSize(f.size))}</span></li>`).join("");
|
|
187
|
+
okBtn.disabled = false;
|
|
188
|
+
okBtn.textContent = "Upload";
|
|
189
|
+
radios.forEach((r) => { r.disabled = false; });
|
|
190
|
+
$("input[name=ws-mode][value=new]", dlg).checked = true;
|
|
191
|
+
|
|
192
|
+
const markChips = () => $$("button", chips).forEach((b) => b.setAttribute("aria-pressed", String(b.textContent === nameIn.value.trim())));
|
|
193
|
+
async function loadSuggestions(fill) {
|
|
194
|
+
const names = await suggestNames(filenames);
|
|
195
|
+
chips.innerHTML = names.map((n) => `<button type="button">${esc(n)}</button>`).join("");
|
|
196
|
+
if (fill || !nameIn.value.trim()) nameIn.value = names[0] || "";
|
|
197
|
+
markChips();
|
|
198
|
+
}
|
|
199
|
+
chips.onclick = (e) => {
|
|
200
|
+
const b = e.target.closest("button");
|
|
201
|
+
if (b) { nameIn.value = b.textContent; markChips(); nameIn.focus(); }
|
|
202
|
+
};
|
|
203
|
+
nameIn.oninput = markChips;
|
|
204
|
+
$("#upload-ws-shuffle").onclick = guard(() => loadSuggestions(false));
|
|
205
|
+
|
|
206
|
+
const syncMode = () => $$("[data-ws-mode]", dlg).forEach((el) => { el.hidden = el.dataset.wsMode !== mode(); });
|
|
207
|
+
radios.forEach((r) => { r.onchange = syncMode; });
|
|
208
|
+
syncMode();
|
|
209
|
+
|
|
210
|
+
nameIn.value = "";
|
|
211
|
+
guard(() => loadSuggestions(true))();
|
|
212
|
+
guard(async () => {
|
|
213
|
+
const spaces = await api("/api/workspaces");
|
|
214
|
+
existing.innerHTML = spaces.map((w) =>
|
|
215
|
+
`<option value="${esc(w.id)}">${esc(w.name)} (${esc(plural(w.document_count, "doc"))})</option>`).join("");
|
|
216
|
+
const radio = $("input[name=ws-mode][value=existing]", dlg);
|
|
217
|
+
radio.disabled = !spaces.length;
|
|
218
|
+
radio.parentElement.title = spaces.length ? "" : "No workspaces yet";
|
|
219
|
+
})();
|
|
220
|
+
|
|
221
|
+
$("#upload-cancel").onclick = () => { if (done) location.href = done; else dlg.close(); };
|
|
222
|
+
$("#upload-form").onsubmit = guard(async (e) => {
|
|
223
|
+
e.preventDefault();
|
|
224
|
+
if (done) { location.href = done; return; }
|
|
225
|
+
let wsId = null;
|
|
226
|
+
if (mode() === "new") {
|
|
227
|
+
const name = nameIn.value.trim();
|
|
228
|
+
if (!name) { nameIn.focus(); throw new Error("Give the workspace a name, or pick a suggestion"); }
|
|
229
|
+
wsId = (await postJSON("/api/workspaces", { name })).id;
|
|
230
|
+
} else if (mode() === "existing") {
|
|
231
|
+
wsId = existing.value;
|
|
232
|
+
}
|
|
233
|
+
const restore = setBusy(okBtn, "Uploading…");
|
|
234
|
+
radios.forEach((r) => { r.disabled = true; });
|
|
235
|
+
const items = $$("li", list);
|
|
236
|
+
const { documents, skipped } = await sendBatch(files, wsId, (i, status, text) => {
|
|
237
|
+
items[i].className = status;
|
|
238
|
+
items[i].lastElementChild.textContent = text;
|
|
239
|
+
if (status === "run") items[i].scrollIntoView({ block: "nearest" });
|
|
240
|
+
});
|
|
241
|
+
restore();
|
|
242
|
+
done = wsId ? `/workspaces/${wsId}` : documents.length === 1 ? `/documents/${documents[0].id}` : "/documents";
|
|
243
|
+
if (!skipped.length) { location.href = done; return; }
|
|
244
|
+
// stay open so the skipped files and their reasons can be read
|
|
245
|
+
$("#upload-summary").textContent = `Added ${plural(documents.length, "document")}. ${skippedMessage(skipped)}`;
|
|
246
|
+
okBtn.textContent = "Continue";
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
dlg.showModal();
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function wireUploads() {
|
|
253
|
+
$$(".upload-input").forEach((input) => input.addEventListener("change", (e) => {
|
|
254
|
+
uploadFiles(e.target.files, { workspaceId: e.target.dataset.workspace });
|
|
255
|
+
e.target.value = "";
|
|
256
|
+
}));
|
|
257
|
+
const overlay = $("#drop-overlay");
|
|
258
|
+
let depth = 0;
|
|
259
|
+
const hasFiles = (e) => Array.from(e.dataTransfer?.types || []).includes("Files");
|
|
260
|
+
window.addEventListener("dragenter", (e) => { if (!hasFiles(e)) return; e.preventDefault(); depth++; overlay.hidden = false; });
|
|
261
|
+
window.addEventListener("dragleave", () => { if (--depth <= 0) { depth = 0; overlay.hidden = true; } });
|
|
262
|
+
window.addEventListener("dragover", (e) => { if (hasFiles(e)) e.preventDefault(); });
|
|
263
|
+
window.addEventListener("drop", (e) => {
|
|
264
|
+
if (!hasFiles(e)) return;
|
|
265
|
+
e.preventDefault(); depth = 0; overlay.hidden = true;
|
|
266
|
+
uploadFiles(e.dataTransfer.files);
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// ------------------------------------------------------------------ model ratings
|
|
271
|
+
const RATING_CLS = { excellent: "excellent", good: "ok", fair: "fair", unsuitable: "bad", unrated: "" };
|
|
272
|
+
|
|
273
|
+
/** Badge for a catalog rating (see llm/catalog.py). */
|
|
274
|
+
function ratingBadge(m) {
|
|
275
|
+
return `<span class="badge ${RATING_CLS[m.rating] || ""}" title="${esc(m.note || "")}">${esc(m.rating_label)}</span>`;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function fmtPrice(m) {
|
|
279
|
+
if (m.price_in == null) return "";
|
|
280
|
+
return `$${m.price_in} / $${m.price_out} per 1M tokens`;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const _verdictCache = new Map();
|
|
284
|
+
/** Ask the server how well `name` suits transcription (works for custom names too). */
|
|
285
|
+
function lookupModel(providerId, name) {
|
|
286
|
+
const key = `${providerId}|${name}`;
|
|
287
|
+
if (!_verdictCache.has(key)) {
|
|
288
|
+
const qs = `provider=${encodeURIComponent(providerId)}&name=${encodeURIComponent(name)}`;
|
|
289
|
+
_verdictCache.set(key, api(`/api/models/lookup?${qs}`).catch(() => null));
|
|
290
|
+
}
|
|
291
|
+
return _verdictCache.get(key);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** One-line HTML verdict for a model name, e.g. under a model input. */
|
|
295
|
+
function verdictHtml(m) {
|
|
296
|
+
if (!m) return "";
|
|
297
|
+
const which = m.match && !m.exact ? ` <span class="muted">(looks like <code>${esc(m.match)}</code>)</span>` : "";
|
|
298
|
+
const status = m.status && m.status !== "current" ? ` <span class="badge">${esc(m.status)}</span>` : "";
|
|
299
|
+
const custom = m.match ? "" : ' <span class="muted">custom name</span>';
|
|
300
|
+
const price = fmtPrice(m) ? ` <span class="muted">· ${esc(fmtPrice(m))} ·</span>` : "";
|
|
301
|
+
return `${ratingBadge(m)}${status}${which}${custom}${price} <span class="muted">${esc(m.note || "")}</span>`;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Keep `out` showing the verdict for whatever is typed into `input` (or its placeholder). */
|
|
305
|
+
function bindModelVerdict(input, out, providerId) {
|
|
306
|
+
let timer;
|
|
307
|
+
const current = () => input.value.trim() || input.placeholder.trim();
|
|
308
|
+
const update = () => {
|
|
309
|
+
clearTimeout(timer);
|
|
310
|
+
timer = setTimeout(async () => {
|
|
311
|
+
const name = current();
|
|
312
|
+
const pid = typeof providerId === "function" ? providerId() : providerId;
|
|
313
|
+
if (!name || !pid) { out.innerHTML = ""; return; }
|
|
314
|
+
const m = await lookupModel(pid, name);
|
|
315
|
+
if (current() === name) out.innerHTML = verdictHtml(m);
|
|
316
|
+
}, 200);
|
|
317
|
+
};
|
|
318
|
+
input.addEventListener("input", update);
|
|
319
|
+
input.addEventListener("change", update);
|
|
320
|
+
update();
|
|
321
|
+
return update;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** Fill a <datalist> with a provider's model options, labelled with their rating. */
|
|
325
|
+
function fillModelDatalist(datalist, options) {
|
|
326
|
+
datalist.innerHTML = options.map((m) =>
|
|
327
|
+
`<option value="${esc(m.name)}" label="${esc(m.rating_label + (m.label ? " · " + m.label : ""))}">`).join("");
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// ------------------------------------------------------------------ LLM picker
|
|
331
|
+
/**
|
|
332
|
+
* Turn a `[data-llm-picker]` block into a working provider/model/prompt picker.
|
|
333
|
+
* The choice is remembered in localStorage and shared between pages.
|
|
334
|
+
*/
|
|
335
|
+
async function initLlmPicker(root) {
|
|
336
|
+
const cfg = await getConfig();
|
|
337
|
+
const provSel = $("[data-provider]", root), modelIn = $("[data-model]", root), promptSel = $("[data-prompt]", root);
|
|
338
|
+
const customBox = $("[data-custom-box]", root), customTa = $("[data-custom]", root), status = $("[data-status]", root);
|
|
339
|
+
const datalist = document.getElementById(modelIn.getAttribute("list"));
|
|
340
|
+
|
|
341
|
+
const providers = [...cfg.providers].sort((a, b) => b.configured - a.configured);
|
|
342
|
+
provSel.innerHTML = providers.map((p) =>
|
|
343
|
+
`<option value="${esc(p.id)}">${esc(p.label)}${p.configured ? "" : " (not configured)"}</option>`).join("");
|
|
344
|
+
promptSel.innerHTML = cfg.prompt_modes.map((m) => `<option value="${esc(m.id)}">${esc(m.label)}</option>`).join("") +
|
|
345
|
+
'<option value="custom">Custom prompt…</option>';
|
|
346
|
+
|
|
347
|
+
const saved = localStorage.getItem("pyocr.provider");
|
|
348
|
+
if (saved && providers.some((p) => p.id === saved)) provSel.value = saved;
|
|
349
|
+
promptSel.value = localStorage.getItem("pyocr.prompt") || "verbatim";
|
|
350
|
+
customTa.value = localStorage.getItem("pyocr.customPrompt") || cfg.prompt_modes[0].prompt;
|
|
351
|
+
|
|
352
|
+
const provider = () => cfg.providers.find((p) => p.id === provSel.value);
|
|
353
|
+
function syncProvider() {
|
|
354
|
+
const p = provider();
|
|
355
|
+
localStorage.setItem("pyocr.provider", p.id);
|
|
356
|
+
modelIn.value = localStorage.getItem(`pyocr.model.${p.id}`) || p.default_model || "";
|
|
357
|
+
modelIn.placeholder = p.model_hint;
|
|
358
|
+
fillModelDatalist(datalist, p.model_options || []);
|
|
359
|
+
status.innerHTML = p.configured ? "" :
|
|
360
|
+
`<span class="warn">Not configured: set ${esc(p.missing.join(", "))}. See <a href="/providers">Providers</a>.</span>`;
|
|
361
|
+
refreshVerdict();
|
|
362
|
+
}
|
|
363
|
+
function syncPrompt() {
|
|
364
|
+
localStorage.setItem("pyocr.prompt", promptSel.value);
|
|
365
|
+
customBox.hidden = promptSel.value !== "custom";
|
|
366
|
+
if (!customBox.hidden) customBox.open = true;
|
|
367
|
+
}
|
|
368
|
+
// Rating of the chosen model (custom names are fine; they just get a heuristic verdict).
|
|
369
|
+
const verdict = document.createElement("div");
|
|
370
|
+
verdict.className = "picker-verdict small";
|
|
371
|
+
status.before(verdict);
|
|
372
|
+
const refreshVerdict = bindModelVerdict(modelIn, verdict, () => provSel.value);
|
|
373
|
+
provSel.addEventListener("change", syncProvider);
|
|
374
|
+
promptSel.addEventListener("change", syncPrompt);
|
|
375
|
+
modelIn.addEventListener("change", () => localStorage.setItem(`pyocr.model.${provider().id}`, modelIn.value.trim()));
|
|
376
|
+
customTa.addEventListener("change", () => localStorage.setItem("pyocr.customPrompt", customTa.value));
|
|
377
|
+
syncProvider();
|
|
378
|
+
syncPrompt();
|
|
379
|
+
|
|
380
|
+
return {
|
|
381
|
+
provider,
|
|
382
|
+
/** Request body for the LLM endpoints; throws if the provider isn't usable. */
|
|
383
|
+
spec(force = false) {
|
|
384
|
+
const p = provider();
|
|
385
|
+
if (!p.configured) throw new Error(`${p.label} is not configured: set ${p.missing.join(", ")}`);
|
|
386
|
+
const body = { provider: p.id, model: modelIn.value.trim() || null, prompt_mode: promptSel.value, force };
|
|
387
|
+
if (body.prompt_mode === "custom") body.custom_prompt = customTa.value;
|
|
388
|
+
return body;
|
|
389
|
+
},
|
|
390
|
+
describe() {
|
|
391
|
+
const p = provider();
|
|
392
|
+
return `${p.label} · ${modelIn.value.trim() || p.default_model || "?"} · ${promptSel.value}`;
|
|
393
|
+
},
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// ------------------------------------------------------------------ jobs
|
|
398
|
+
/** 7 → "7s", 95 → "1m 35s", 4000 → "1h 6m". */
|
|
399
|
+
function fmtDuration(sec) {
|
|
400
|
+
const s = Math.max(0, Math.round(sec));
|
|
401
|
+
if (s < 60) return `${s}s`;
|
|
402
|
+
if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`;
|
|
403
|
+
return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** $0.0042 / $1.23: more digits for the sub-cent amounts a single page costs. */
|
|
407
|
+
function fmtUSD(x) {
|
|
408
|
+
if (x === 0) return "$0";
|
|
409
|
+
return x < 0.01 ? (x < 0.0001 ? "<$0.0001" : `$${x.toFixed(4)}`) : `$${x.toFixed(2)}`;
|
|
410
|
+
}
|
|
411
|
+
/** ₹0.39 / ₹1,23,456.78 (Indian digit grouping). */
|
|
412
|
+
function fmtINR(x) {
|
|
413
|
+
if (x === 0) return "₹0";
|
|
414
|
+
if (x < 0.01) return "<₹0.01";
|
|
415
|
+
return "₹" + x.toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
|
416
|
+
}
|
|
417
|
+
/** "$0.42 (₹38.85)" for a `cost` object from the API (Services.cost / Job.cost), with the basis in a tooltip. */
|
|
418
|
+
function costHtml(cost) {
|
|
419
|
+
if (!cost) return "";
|
|
420
|
+
const tip = `List price for ${cost.price_model}: $${cost.price_in} in / $${cost.price_out} out per 1M tokens, ` +
|
|
421
|
+
`at ₹${cost.usd_inr_rate} per $ (USD_INR_RATE). Excludes taxes such as GST and batch/caching discounts; ` +
|
|
422
|
+
`a self-hosted model costs nothing.`;
|
|
423
|
+
return `<span class="cost" title="${esc(tip)}">${fmtUSD(cost.usd)} (${fmtINR(cost.inr)})</span>`;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function jobHtml(job, docName) {
|
|
427
|
+
const pctDone = job.total ? Math.round((job.done / job.total) * 100) : 0;
|
|
428
|
+
const ok = job.done - job.failed;
|
|
429
|
+
// "done" with some failed pages is a partial success: amber, not green.
|
|
430
|
+
const statusCls = job.status === "done" && job.failed ? "scan"
|
|
431
|
+
: { done: "ok", running: "run", queued: "run", failed: "bad", cancelled: "" }[job.status] || "";
|
|
432
|
+
const status = job.status === "done" && job.failed ? "done with errors" : job.status;
|
|
433
|
+
const dur = job.started_at ? fmtDuration((job.finished_at || Date.now() / 1000) - job.started_at) : "";
|
|
434
|
+
const rate = job.seconds_per_page != null ? ` · ~${fmtDuration(job.seconds_per_page)}/page` : "";
|
|
435
|
+
const eta = job.eta_seconds != null ? ` · ~${fmtDuration(job.eta_seconds)} left` : "";
|
|
436
|
+
const tokens = job.kind === "llm" && (job.input_tokens || job.output_tokens)
|
|
437
|
+
? ` · ${fmtInt(job.input_tokens)} in / ${fmtInt(job.output_tokens)} out tokens` : "";
|
|
438
|
+
const c = job.cost;
|
|
439
|
+
const projected = c && c.projected_usd != null
|
|
440
|
+
? ` · <span class="cost" title="Assumes the remaining pages cost what the pages so far did; cached pages make it lower.">` +
|
|
441
|
+
`~${fmtUSD(c.projected_usd)} (${fmtINR(c.projected_inr)}) for the whole job</span>` : "";
|
|
442
|
+
const cost = c ? ` · ${costHtml(c)}${projected}`
|
|
443
|
+
: job.kind === "llm" ? ` · <span title="This model isn't in the catalog, so no price is known.">cost unknown</span>` : "";
|
|
444
|
+
const failed = job.failed ? `<span class="err">${job.failed} failed</span>` : "0 failed";
|
|
445
|
+
const pages = (ps) => "p" + ps.map((p) => p + 1).join(", p");
|
|
446
|
+
const working = job.current_pages.length ? ` · working on ${pages(job.current_pages)}` : "";
|
|
447
|
+
const waiting = (job.waiting_pages || []).length ? ` · waiting for a model slot: ${pages(job.waiting_pages)}` : "";
|
|
448
|
+
const errors = job.errors.length
|
|
449
|
+
? `<details class="small"><summary class="err">${job.failed} page(s) failed</summary><ul>${job.errors.map((e) => `<li>${esc(e)}</li>`).join("")}</ul></details>` : "";
|
|
450
|
+
const active = job.status === "running" || job.status === "queued";
|
|
451
|
+
const w = (n) => (job.total ? (n / job.total) * 100 : 0).toFixed(2);
|
|
452
|
+
// Polling re-renders this markup; a negative delay tied to the clock keeps the
|
|
453
|
+
// running animations (styles.css "Motion") in phase instead of restarting.
|
|
454
|
+
const phase = active ? ` style="--phase:-${(Date.now() % 2800) / 1000}s"` : "";
|
|
455
|
+
return `<div class="job${active ? " is-active" : ""}" data-job="${job.id}"${phase}>
|
|
456
|
+
<div class="job-head">
|
|
457
|
+
<span class="badge ${statusCls}">${status}</span>
|
|
458
|
+
<b>${esc(job.label)}</b>
|
|
459
|
+
${docName ? `<a href="/documents/${job.doc_id}">${esc(docName)}</a>` : ""}
|
|
460
|
+
<div class="spacer"></div>
|
|
461
|
+
${active ? `<button class="link" data-cancel="${job.id}">cancel</button>` : ""}
|
|
462
|
+
</div>
|
|
463
|
+
<div class="jobbar" role="progressbar" aria-valuemin="0" aria-valuemax="${job.total}" aria-valuenow="${job.done}"
|
|
464
|
+
aria-valuetext="${job.done} of ${job.total} pages, ${job.failed} failed">
|
|
465
|
+
<span class="jobbar-ok" style="width:${w(ok)}%"></span><span class="jobbar-fail" style="width:${w(job.failed)}%"></span>
|
|
466
|
+
</div>
|
|
467
|
+
<div class="small">${job.done}/${job.total} pages (${pctDone}%) · ${job.cached} from cache · ${failed} · ${dur}${rate}${eta}${tokens}${cost}${working}${waiting}</div>
|
|
468
|
+
${errors}
|
|
469
|
+
</div>`;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** Poll a job until it finishes, calling onUpdate(job) each time. */
|
|
473
|
+
async function watchJob(jobId, onUpdate, intervalMs = 1000) {
|
|
474
|
+
for (;;) {
|
|
475
|
+
const job = await api(`/api/jobs/${jobId}`);
|
|
476
|
+
onUpdate(job);
|
|
477
|
+
if (!["running", "queued"].includes(job.status)) return job;
|
|
478
|
+
await new Promise((r) => setTimeout(r, intervalMs));
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
document.addEventListener("click", guard(async (e) => {
|
|
483
|
+
const btn = e.target.closest("[data-cancel]");
|
|
484
|
+
if (btn) {
|
|
485
|
+
await postJSON(`/api/jobs/${btn.dataset.cancel}/cancel`);
|
|
486
|
+
toast("Cancelling…");
|
|
487
|
+
}
|
|
488
|
+
}));
|
|
489
|
+
|
|
490
|
+
wireUploads();
|
|
491
|
+
|
|
492
|
+
// ------------------------------------------------------------------ theme
|
|
493
|
+
/* The inline script in base.html applies the saved theme before first paint;
|
|
494
|
+
* this wires the toggle button (system -> light -> dark -> system ...) and keeps
|
|
495
|
+
* "system" in sync if the OS switches between light and dark while the page is open. */
|
|
496
|
+
(function wireTheme() {
|
|
497
|
+
const root = document.documentElement;
|
|
498
|
+
const media = window.matchMedia("(prefers-color-scheme: dark)");
|
|
499
|
+
const labels = { system: "Theme: match system", light: "Theme: light", dark: "Theme: dark" };
|
|
500
|
+
function apply(pref, animate) {
|
|
501
|
+
if (animate) {
|
|
502
|
+
root.classList.add("theme-switching");
|
|
503
|
+
setTimeout(() => root.classList.remove("theme-switching"), 250);
|
|
504
|
+
}
|
|
505
|
+
root.dataset.themePref = pref;
|
|
506
|
+
root.dataset.theme = pref === "dark" || (pref === "system" && media.matches) ? "dark" : "light";
|
|
507
|
+
const btn = $("#theme-toggle");
|
|
508
|
+
if (btn) btn.title = `${labels[pref]} (click to change)`;
|
|
509
|
+
}
|
|
510
|
+
const order = ["system", "light", "dark"];
|
|
511
|
+
$("#theme-toggle")?.addEventListener("click", () => {
|
|
512
|
+
const next = order[(order.indexOf(root.dataset.themePref) + 1) % order.length];
|
|
513
|
+
try { localStorage.setItem("pyocr.theme", next); } catch (_) { /* private mode */ }
|
|
514
|
+
apply(next, true);
|
|
515
|
+
toast(labels[next]);
|
|
516
|
+
});
|
|
517
|
+
media.addEventListener("change", () => { if (root.dataset.themePref === "system") apply("system", true); });
|
|
518
|
+
apply(root.dataset.themePref || "system", false);
|
|
519
|
+
})();
|
|
520
|
+
|
|
521
|
+
// ------------------------------------------------------------------ diff
|
|
522
|
+
/** HTML for a word diff from the compare API. Leading line breaks stay outside
|
|
523
|
+
* the coloured spans so they don't leave a highlighted sliver at line ends. */
|
|
524
|
+
function renderDiff(segments) {
|
|
525
|
+
const lead = (t) => t.match(/^\n*/)[0];
|
|
526
|
+
const wrap = (text, cls, title) => `${lead(text)} <span class="${cls}" title="${title}">${esc(text.slice(lead(text).length))}</span> `;
|
|
527
|
+
return segments.map((s) => {
|
|
528
|
+
switch (s.op) {
|
|
529
|
+
case "equal": return esc(s.ref);
|
|
530
|
+
case "delete": return wrap(s.ref, "del", "in reference only");
|
|
531
|
+
case "insert": return wrap(s.hyp, "ins", "in candidate only");
|
|
532
|
+
default: {
|
|
533
|
+
const l = lead(s.ref).length >= lead(s.hyp).length ? lead(s.ref) : lead(s.hyp);
|
|
534
|
+
return `${l} <span class="rep"><s>${esc(s.ref.trimStart())}</s>→<ins>${esc(s.hyp.trimStart())}</ins></span> `;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}).join(" ");
|
|
538
|
+
}
|