Skip to content

Build your personal knowledge base with Trilium Notes

fix(standalone): show OCR text, and stop offering to extract it where it cannot run

Elian Doran69fd4bd17e86
diff --git a/apps/client/src/widgets/dialogs/ocr_text.spec.tsx b/apps/client/src/widgets/dialogs/ocr_text.spec.tsx
new file mode 100644
index 0000000000..91d791297d
--- /dev/null
+++ b/apps/client/src/widgets/dialogs/ocr_text.spec.tsx
@@ -0,0 +1,85 @@
+/**
+ * The dialog showing the text OCR pulled out of an image or a document.
+ *
+ * Reading and extracting are two different capabilities: the text is stored on the blob and travels
+ * with it, so any client can show it, but running the extraction needs the engine only the server
+ * has. What is held here is that the dialog offers exactly what the client it is running in can do.
+ */
+import { act } from "preact/test-utils";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import Component from "../../components/component";
+import { renderInto } from "../../test/render";
+import { ParentComponent } from "../react/react_utils";
+import OcrTextDialog from "./ocr_text";
+
+const mocks = vi.hoisted(() => ({ standalone: false }));
+
+vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));
+vi.mock("../../components/app_context", () => ({ default: { triggerCommand: vi.fn() } }));
+// Answer the dialog's own request and nothing else: the modal's shortcut hints go through the same
+// service, and handing them this payload instead of the list they expect throws inside their fetch.
+vi.mock("../../services/server", () => ({
+ default: {
+ get: vi.fn(async (url: string) => (url.endsWith("/text")
+ ? { success: true, hasOcr: true, text: "scanned text" }
+ : [])),
+ post: vi.fn()
+ }
+}));
+
+// `isStandalone` is a const in the target, read here through a getter so a scenario can flip which
+// kind of client we are pretending to be. Partial-mock, so the rest of utils stays real.
+vi.mock("../../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../services/utils")>()),
+ get isStandalone() {
+ return mocks.standalone;
+ }
+}));
+
+/** Opens the dialog on a note, as the command that shows it does, and waits for the text to arrive. */
+async function open() {
+ const host = new Component();
+ renderInto(
+ <ParentComponent.Provider value={host}>
+ <OcrTextDialog />
+ </ParentComponent.Provider>
+ );
+
+ await act(async () => {
+ await host.handleEvent("showOcrTextDialog", {
+ textUrl: "ocr/notes/n1/text",
+ processUrl: "ocr/process-note/n1"
+ });
+ });
+}
+
+function footerButtons(): string[] {
+ return [ ...document.querySelectorAll(".ocr-text-modal .modal-footer button") ]
+ .map((button) => button.textContent?.trim() ?? "");
+}
+
+describe("OcrTextDialog", () => {
+ beforeEach(() => {
+ mocks.standalone = false;
+ document.body.innerHTML = "";
+ });
+
+ it("shows the text, and offers to extract it again where an engine can", async () => {
+ await open();
+
+ expect(document.querySelector(".ocr-text-modal-content")?.textContent).toBe("scanned text");
+ expect(footerButtons()).toContain("ocr.process_now");
+ });
+
+ it("drops the offer to extract in standalone, which has no engine to run", async () => {
+ mocks.standalone = true;
+ await open();
+
+ // The text still shows: it was extracted wherever OCR ran and synced here with the blob.
+ expect(document.querySelector(".ocr-text-modal-content")?.textContent).toBe("scanned text");
+ expect(footerButtons()).not.toContain("ocr.process_now");
+ // Copying is not extraction, and stays.
+ expect(footerButtons()).toContain("info.copy_to_clipboard");
+ });
+});
diff --git a/apps/client/src/widgets/dialogs/ocr_text.tsx b/apps/client/src/widgets/dialogs/ocr_text.tsx
index d7c5036bae..44ee6afedb 100644
--- a/apps/client/src/widgets/dialogs/ocr_text.tsx
+++ b/apps/client/src/widgets/dialogs/ocr_text.tsx
@@ -8,7 +8,7 @@ import { copyTextWithToast } from "../../services/clipboard_ext";
import { t } from "../../services/i18n";
import server from "../../services/server";
import toast from "../../services/toast";
-import { randomString } from "../../services/utils";
+import { isStandalone, randomString } from "../../services/utils";
import Button from "../react/Button";
import { useTriliumEvent } from "../react/hooks";
import Modal from "../react/Modal";
@@ -139,13 +139,17 @@ function TextRepresentationModal({ textUrl, processUrl, onHidden }: TextRepresen
const footer = state.kind !== "loading" && (
<>
- <Button
- icon={processing ? "bx-loader-alt bx-spin" : "bx-refresh"}
- text={processing ? t("ocr.processing") : t("ocr.process_now")}
- size="small"
- disabled={processing}
- onClick={processOCR}
- />
+ {/* Extracting text needs the OCR engine, which only the server has: standalone can show
+ what was extracted elsewhere and synced here, but cannot run it itself. */}
+ {!isStandalone && (
+ <Button
+ icon={processing ? "bx-loader-alt bx-spin" : "bx-refresh"}
+ text={processing ? t("ocr.processing") : t("ocr.process_now")}
+ size="small"
+ disabled={processing}
+ onClick={processOCR}
+ />
+ )}
{state.kind === "loaded" && (
<Button
icon="bx-copy"
diff --git a/apps/client/src/widgets/type_widgets/options/media.spec.tsx b/apps/client/src/widgets/type_widgets/options/media.spec.tsx
index 99c637a801..ed0367f44c 100644
--- a/apps/client/src/widgets/type_widgets/options/media.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/media.spec.tsx
@@ -14,7 +14,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
*/
const mocks = vi.hoisted(() => ({
stored: {} as Record<string, string>,
- saved: vi.fn<(name: string, value: string) => void>()
+ saved: vi.fn<(name: string, value: string) => void>(),
+ standalone: false
+}));
+
+// `isStandalone` is a const in the target, read here through a getter so a scenario can flip which
+// kind of client we are pretending to be. Partial-mock, so the rest of utils stays real.
+vi.mock("../../../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/utils")>()),
+ get isStandalone() {
+ return mocks.standalone;
+ }
}));
// i18next is never initialised for these tests and answers `undefined` until it is, which would
@@ -127,6 +137,7 @@ async function choose(title: string, label: string) {
}
beforeEach(() => {
+ mocks.standalone = false;
host = document.body.appendChild(document.createElement("div"));
});
@@ -210,3 +221,22 @@ describe("the images card", () => {
expect(mocks.saved.mock.calls.map(([ name ]) => name)).toEqual([ "imagePngHandling", "imageJpegHandling" ]);
});
});
+
+describe("the OCR card", () => {
+ // Extracting text needs the engine the server holds. A standalone client reads OCR text that was
+ // extracted elsewhere and synced to it, so the settings governing extraction stay — they are
+ // synced options, read by whichever server does the work — but the button that would run it here
+ // goes, rather than answering a press with a 404.
+ it("offers batch processing only where OCR can actually run", () => {
+ open();
+ expect(host.querySelector(".media-batch-ocr")).not.toBeNull();
+ expect(host.querySelector(".media-ocr .tn-card-option")).not.toBeNull();
+
+ render(null, host);
+ mocks.standalone = true;
+ open();
+ expect(host.querySelector(".media-batch-ocr")).toBeNull();
+ // The card itself stays: its two settings govern the extraction wherever it happens.
+ expect(host.querySelector(".media-ocr .tn-card-option")).not.toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/media.tsx b/apps/client/src/widgets/type_widgets/options/media.tsx
index d229b7ac27..754a353ac7 100644
--- a/apps/client/src/widgets/type_widgets/options/media.tsx
+++ b/apps/client/src/widgets/type_widgets/options/media.tsx
@@ -6,7 +6,7 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
import toast from "../../../services/toast";
-import { isElectron } from "../../../services/utils";
+import { isElectron, isStandalone } from "../../../services/utils";
import {
AUTOMATIC_IMAGE_COMPRESSION_DEFAULTS,
type ImageCompressionToolOptions,
@@ -172,7 +172,9 @@ function OcrSettings() {
/>
</CardOption>
- <BatchProcessing />
+ {/* Running OCR needs the engine the server holds; a standalone client only ever
+ reads text extracted elsewhere and synced to it. */}
+ {!isStandalone && <BatchProcessing />}
</Card>
</div>
diff --git a/apps/server/src/routes/api/ocr.spec.ts b/apps/server/src/routes/api/ocr.spec.ts
index 176e482758..2224be6bb1 100644
--- a/apps/server/src/routes/api/ocr.spec.ts
+++ b/apps/server/src/routes/api/ocr.spec.ts
@@ -1,4 +1,4 @@
-import { becca, cls, getSql, note_service as noteService } from "@triliumnext/core";
+import { cls, note_service as noteService } from "@triliumnext/core";
import type { Request } from "express";
import { beforeAll, describe, expect, it, vi } from "vitest";
@@ -84,24 +84,4 @@ describe("OCR API", () => {
});
});
- describe("OCR text retrieval", () => {
- it("returns 404 for a missing note / attachment", async () => {
- expect(await ocrRoutes.getNoteOCRText({ params: { noteId: "missing" } } as unknown as Request<{ noteId: string }>))
- .toEqual([404, { success: false, message: "Note not found" }]);
- expect(await ocrRoutes.getAttachmentOCRText({ params: { attachmentId: "missing" } } as unknown as Request<{ attachmentId: string }>))
- .toEqual([404, { success: false, message: "Attachment not found" }]);
- });
-
- it("reports no OCR text when none is stored", async () => {
- const result = await ocrRoutes.getNoteOCRText({ params: { noteId } } as unknown as Request<{ noteId: string }>);
- expect(result).toEqual({ success: true, text: "", hasOcr: false });
- });
-
- it("returns stored OCR text from the blob", async () => {
- const blobId = becca.getNoteOrThrow(noteId).blobId;
- cls.init(() => getSql().execute("UPDATE blobs SET textRepresentation = ? WHERE blobId = ?", ["scanned text", blobId]));
- const result = await ocrRoutes.getNoteOCRText({ params: { noteId } } as unknown as Request<{ noteId: string }>);
- expect(result).toEqual({ success: true, text: "scanned text", hasOcr: true });
- });
- });
});
diff --git a/apps/server/src/routes/api/ocr.ts b/apps/server/src/routes/api/ocr.ts
index 32dac0e0ad..99303828d6 100644
--- a/apps/server/src/routes/api/ocr.ts
+++ b/apps/server/src/routes/api/ocr.ts
@@ -1,10 +1,9 @@
-import type { OCRProcessResponse, TextRepresentationResponse } from "@triliumnext/commons";
+import type { OCRProcessResponse } from "@triliumnext/commons";
import { options } from "@triliumnext/core";
import type { Request } from "express";
import { becca } from "@triliumnext/core";
import ocrService from "../../services/ocr/ocr_service.js";
-import sql from "../../services/sql.js";
function getMinConfidenceThreshold(): number {
const minConfidence = options.getOption('ocrMinConfidence') ?? 0;
@@ -183,73 +182,9 @@ async function getBatchProgress() {
return ocrService.getBatchProgress();
}
-/**
- * @swagger
- * /api/ocr/notes/{noteId}/text:
- * get:
- * summary: Get OCR text for a specific note
- * operationId: ocr-get-note-text
- * parameters:
- * - name: noteId
- * in: path
- * required: true
- * schema:
- * type: string
- * description: Note ID to get OCR text for
- * responses:
- * 200:
- * description: OCR text retrieved successfully
- * 404:
- * description: Note not found
- * tags: ["ocr"]
- */
-function getTextRepresentation(blobId: string | undefined): TextRepresentationResponse {
- let ocrText: string | null = null;
-
- if (blobId) {
- const result = sql.getRow<{
- textRepresentation: string | null;
- }>(`
- SELECT textRepresentation
- FROM blobs
- WHERE blobId = ?
- `, [blobId]);
-
- if (result) {
- ocrText = result.textRepresentation;
- }
- }
-
- return {
- success: true,
- text: ocrText || '',
- hasOcr: !!ocrText
- };
-}
-
-async function getNoteOCRText(req: Request<{ noteId: string }>) {
- const note = becca.getNote(req.params.noteId);
- if (!note) {
- return [404, { success: false, message: 'Note not found' }];
- }
-
- return getTextRepresentation(note.blobId);
-}
-
-async function getAttachmentOCRText(req: Request<{ attachmentId: string }>) {
- const attachment = becca.getAttachment(req.params.attachmentId);
- if (!attachment) {
- return [404, { success: false, message: 'Attachment not found' }];
- }
-
- return getTextRepresentation(attachment.blobId);
-}
-
export default {
processNoteOCR,
processAttachmentOCR,
batchProcessOCR,
getBatchProgress,
- getNoteOCRText,
- getAttachmentOCRText
};
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index ab3e22181a..833eba9729 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -203,8 +203,6 @@ function register(app: express.Application) {
asyncApiRoute(PST, "/api/ocr/process-attachment/:attachmentId", ocrRoute.processAttachmentOCR);
asyncApiRoute(PST, "/api/ocr/batch-process", ocrRoute.batchProcessOCR);
asyncApiRoute(GET, "/api/ocr/batch-progress", ocrRoute.getBatchProgress);
- asyncApiRoute(GET, "/api/ocr/notes/:noteId/text", ocrRoute.getNoteOCRText);
- asyncApiRoute(GET, "/api/ocr/attachments/:attachmentId/text", ocrRoute.getAttachmentOCRText);
app.use("", router);
}
diff --git a/packages/trilium-core/src/routes/api/ocr.spec.ts b/packages/trilium-core/src/routes/api/ocr.spec.ts
new file mode 100644
index 0000000000..4b63231243
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/ocr.spec.ts
@@ -0,0 +1,68 @@
+import type { TextRepresentationResponse } from "@triliumnext/commons";
+import { beforeAll, describe, expect, it } from "vitest";
+
+import becca from "../../becca/becca.js";
+import * as cls from "../../services/context.js";
+import { getSql } from "../../services/sql/index.js";
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared OCR read routes through {@link CoreApiTester} (no Express), so this spec runs
+ * under both the node and standalone (WASM) suites — the second being the point of sharing them:
+ * the text is written by the server's OCR engine but travels with the blob, so a synced client has
+ * it too.
+ */
+let api: CoreApiTester;
+
+interface AttachmentPojo {
+ attachmentId: string;
+}
+
+/** Writes OCR text straight onto a blob, standing in for what the engine would have stored. */
+function storeOcrText(blobId: string | undefined, text: string) {
+ cls.init(() => getSql().execute("UPDATE blobs SET textRepresentation = ? WHERE blobId = ?", [ text, blobId ]));
+}
+
+describe("OCR text API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ it("returns the text stored for a note, and says when there is none", async () => {
+ const { noteId } = await createTextNote(api, { content: "<p>a scan</p>" });
+
+ const before = await api.get<TextRepresentationResponse>(`/api/ocr/notes/${noteId}/text`);
+ expect(before.status).toBe(200);
+ expect(before.body).toEqual({ success: true, text: "", hasOcr: false });
+
+ storeOcrText(becca.getNoteOrThrow(noteId).blobId, "scanned text");
+
+ const after = await api.get<TextRepresentationResponse>(`/api/ocr/notes/${noteId}/text`);
+ expect(after.body).toEqual({ success: true, text: "scanned text", hasOcr: true });
+ });
+
+ it("returns the text stored for an attachment", async () => {
+ const { noteId } = await createTextNote(api, { title: "Has a scan" });
+ expect((await api.post(`/api/notes/${noteId}/attachments`, {
+ body: { role: "file", mime: "image/png", title: "scan.png", content: "x" }
+ })).status).toBe(204);
+ const list = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);
+ const { attachmentId } = list.body[0];
+
+ storeOcrText(becca.getAttachmentOrThrow(attachmentId).blobId, "text on the scan");
+
+ const res = await api.get<TextRepresentationResponse>(`/api/ocr/attachments/${attachmentId}/text`);
+ expect(res.body).toEqual({ success: true, text: "text on the scan", hasOcr: true });
+ });
+
+ it("404s for a missing note or attachment", async () => {
+ const note = await api.get<TextRepresentationResponse>("/api/ocr/notes/missingNote123/text");
+ expect(note.status).toBe(404);
+ expect(note.body).toEqual({ success: false, message: "Note not found" });
+
+ const attachment = await api.get<TextRepresentationResponse>("/api/ocr/attachments/missingAttachment123/text");
+ expect(attachment.status).toBe(404);
+ expect(attachment.body).toEqual({ success: false, message: "Attachment not found" });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/ocr.ts b/packages/trilium-core/src/routes/api/ocr.ts
new file mode 100644
index 0000000000..bda57c728e
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/ocr.ts
@@ -0,0 +1,63 @@
+import type { TextRepresentationResponse } from "@triliumnext/commons";
+import type { Request } from "express";
+
+import becca from "../../becca/becca.js";
+import { getSql } from "../../services/sql/index.js";
+
+/** The `[status, body]` tuple the result handler turns into a 404. */
+type NotFound = [number, { success: false; message: string }];
+
+/**
+ * Reading the text OCR pulled out of a note's file.
+ *
+ * Only the reads are shared. Extracting the text needs the OCR engine, which lives in the server —
+ * but the result is stored on the blob and travels with it, so a client that has only synced the
+ * database still has the text and can show (and search) it.
+ */
+function getNoteOCRText(req: Request<{ noteId: string }>): TextRepresentationResponse | NotFound {
+ const note = becca.getNote(req.params.noteId);
+ if (!note) {
+ return [ 404, { success: false, message: "Note not found" } ];
+ }
+
+ return getTextRepresentation(note.blobId);
+}
+
+/** The attachment counterpart of {@link getNoteOCRText}. */
+function getAttachmentOCRText(req: Request<{ attachmentId: string }>): TextRepresentationResponse | NotFound {
+ const attachment = becca.getAttachment(req.params.attachmentId);
+ if (!attachment) {
+ return [ 404, { success: false, message: "Attachment not found" } ];
+ }
+
+ return getTextRepresentation(attachment.blobId);
+}
+
+function getTextRepresentation(blobId: string | undefined): TextRepresentationResponse {
+ let ocrText: string | null = null;
+
+ if (blobId) {
+ const result = getSql().getRow<{
+ textRepresentation: string | null;
+ }>(/*sql*/`
+ SELECT textRepresentation
+ FROM blobs
+ WHERE blobId = ?
+ `, [ blobId ]);
+
+ if (result) {
+ ocrText = result.textRepresentation;
+ }
+ }
+
+ return {
+ success: true,
+ text: ocrText || "",
+ hasOcr: !!ocrText
+ };
+}
+
+export default {
+ getNoteOCRText,
+ getAttachmentOCRText
+};
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 27bc1db88e..7cf8983fbe 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -35,6 +35,7 @@ import backupRoute from "./api/backup";
import passwordApiRoute from "./api/password";
import loginApiRoute from "./api/login";
import fontsRoute from "./api/fonts";
+import ocrRoute from "./api/ocr";
// TODO: Deduplicate with routes.ts
const GET = "get",
@@ -262,6 +263,11 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout
route(GET, "/api/revisions/:revisionId/download", [checkApiAuthOrElectron], revisionsApiRoute.downloadRevision);
route(PUT, "/api/notes/:noteId/file", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateFile, apiResultHandler);
route(PUT, "/api/attachments/:attachmentId/file", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateAttachment, apiResultHandler);
+
+ // Reading the OCR text only. Extracting it needs the engine, which stays in the server — but the
+ // text is stored on the blob and syncs with it, so every client can show what was extracted.
+ apiRoute(GET, "/api/ocr/notes/:noteId/text", ocrRoute.getNoteOCRText);
+ apiRoute(GET, "/api/ocr/attachments/:attachmentId/text", ocrRoute.getAttachmentOCRText);
//#endregion
//#region Export