Skip to content

Build your personal knowledge base with Trilium Notes

feat(ocr): integrate viewing attachment OCR

Elian Doranf163cacddc37
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 104b960d51..c7dd38bd19 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2094,7 +2094,8 @@
"process_now": "Process OCR",
"processing": "Processing...",
"processing_started": "OCR processing has been started. Please wait a moment and refresh.",
- "processing_failed": "Failed to start OCR processing"
+ "processing_failed": "Failed to start OCR processing",
+ "view_extracted_text": "View extracted text (OCR)"
},
"command_palette": {
"tree-action-name": "Tree: {{name}}",
diff --git a/apps/client/src/widgets/type_widgets/Attachment.tsx b/apps/client/src/widgets/type_widgets/Attachment.tsx
index 041814589c..381313d6ba 100644
--- a/apps/client/src/widgets/type_widgets/Attachment.tsx
+++ b/apps/client/src/widgets/type_widgets/Attachment.tsx
@@ -27,8 +27,10 @@ import { FormDropdownDivider, FormListItem } from "../react/FormList";
import HelpButton from "../react/HelpButton";
import { useTriliumEvent } from "../react/hooks";
import Icon from "../react/Icon";
+import Modal from "../react/Modal";
import NoteLink from "../react/NoteLink";
import { ParentComponent, refToJQuerySelector } from "../react/react_utils";
+import { TextRepresentation } from "./ReadOnlyTextRepresentation";
import { TypeWidgetProps } from "./type_widget";
/**
@@ -141,6 +143,8 @@ export function AttachmentDetail({ note, viewScope }: TypeWidgetProps) {
function AttachmentInfo({ attachment, isFullDetail }: { attachment: FAttachment, isFullDetail?: boolean }) {
const contentWrapper = useRef<HTMLDivElement>(null);
+ const [ ocrModalShown, setOcrModalShown ] = useState(false);
+ const supportsOcr = attachment.role === "image" || attachment.role === "file";
function refresh() {
content_renderer.getRenderedContent(attachment, { imageHasZoom: isFullDetail })
@@ -181,7 +185,11 @@ function AttachmentInfo({ attachment, isFullDetail }: { attachment: FAttachment,
<div className="attachment-detail-widget">
<div className={`attachment-detail-wrapper ${isFullDetail ? "full-detail" : "list-view"} ${attachment.utcDateScheduledForErasureSince ? "scheduled-for-deletion" : ""}`}>
<div className="attachment-title-line">
- <AttachmentActions attachment={attachment} copyAttachmentLinkToClipboard={copyAttachmentLinkToClipboard} />
+ <AttachmentActions
+ attachment={attachment}
+ copyAttachmentLinkToClipboard={copyAttachmentLinkToClipboard}
+ onShowOcr={supportsOcr ? () => setOcrModalShown(true) : undefined}
+ />
<h4 className="attachment-title">
{!isFullDetail ? (
<NoteLink
@@ -207,6 +215,22 @@ function AttachmentInfo({ attachment, isFullDetail }: { attachment: FAttachment,
{attachment.utcDateScheduledForErasureSince && <DeletionAlert utcDateScheduledForErasureSince={attachment.utcDateScheduledForErasureSince} />}
<div ref={contentWrapper} className="attachment-content-wrapper" />
</div>
+
+ {supportsOcr && (
+ <Modal
+ className="ocr-text-modal"
+ title={t("ocr.extracted_text_title")}
+ show={ocrModalShown}
+ onHidden={() => setOcrModalShown(false)}
+ size="lg"
+ scrollable
+ >
+ <TextRepresentation
+ textUrl={`ocr/attachments/${attachment.attachmentId}/text`}
+ processUrl={`ocr/process-attachment/${attachment.attachmentId}`}
+ />
+ </Modal>
+ )}
</div>
);
}
@@ -228,7 +252,7 @@ function DeletionAlert({ utcDateScheduledForErasureSince }: { utcDateScheduledFo
);
}
-function AttachmentActions({ attachment, copyAttachmentLinkToClipboard }: { attachment: FAttachment, copyAttachmentLinkToClipboard: () => void }) {
+function AttachmentActions({ attachment, copyAttachmentLinkToClipboard, onShowOcr }: { attachment: FAttachment, copyAttachmentLinkToClipboard: () => void, onShowOcr?: () => void }) {
const isElectron = utils.isElectron();
const fileUploadRef = useRef<HTMLInputElement>(null);
@@ -262,6 +286,12 @@ function AttachmentActions({ attachment, copyAttachmentLinkToClipboard }: { atta
icon="bx bx-link"
onClick={copyAttachmentLinkToClipboard}
>{t("attachments_actions.copy_link_to_clipboard")}</FormListItem>
+ {onShowOcr && (
+ <FormListItem
+ icon="bx bx-text"
+ onClick={onShowOcr}
+ >{t("ocr.view_extracted_text")}</FormListItem>
+ )}
<FormDropdownDivider />
<FormListItem
diff --git a/apps/client/src/widgets/type_widgets/ReadOnlyTextRepresentation.tsx b/apps/client/src/widgets/type_widgets/ReadOnlyTextRepresentation.tsx
index 9eaec33f4c..9ee376f977 100644
--- a/apps/client/src/widgets/type_widgets/ReadOnlyTextRepresentation.tsx
+++ b/apps/client/src/widgets/type_widgets/ReadOnlyTextRepresentation.tsx
@@ -14,7 +14,23 @@ type State =
| { kind: "empty" }
| { kind: "error"; message: string };
+interface TextRepresentationProps {
+ /** The API path to fetch OCR text from (e.g. `ocr/notes/{id}/text`). */
+ textUrl: string;
+ /** The API path to trigger OCR processing (e.g. `ocr/process-note/{id}`). */
+ processUrl: string;
+}
+
export default function ReadOnlyTextRepresentation({ note }: TypeWidgetProps) {
+ return (
+ <TextRepresentation
+ textUrl={`ocr/notes/${note.noteId}/text`}
+ processUrl={`ocr/process-note/${note.noteId}`}
+ />
+ );
+}
+
+export function TextRepresentation({ textUrl, processUrl }: TextRepresentationProps) {
const [ state, setState ] = useState<State>({ kind: "loading" });
const [ processing, setProcessing ] = useState(false);
@@ -22,7 +38,7 @@ export default function ReadOnlyTextRepresentation({ note }: TypeWidgetProps) {
setState({ kind: "loading" });
try {
- const response = await server.get<TextRepresentationResponse>(`ocr/notes/${note.noteId}/text`);
+ const response = await server.get<TextRepresentationResponse>(textUrl);
if (!response.success) {
setState({ kind: "error", message: response.message || t("ocr.failed_to_load") });
@@ -41,12 +57,12 @@ export default function ReadOnlyTextRepresentation({ note }: TypeWidgetProps) {
}
}
- useEffect(() => { fetchText(); }, [ note.noteId ]);
+ useEffect(() => { fetchText(); }, [ textUrl ]);
async function processOCR() {
setProcessing(true);
try {
- const response = await server.post<{ success: boolean; message?: string }>(`ocr/process-note/${note.noteId}`, { forceReprocess: true });
+ const response = await server.post<{ success: boolean; message?: string }>(processUrl, { forceReprocess: true });
if (response.success) {
toast.showMessage(t("ocr.processing_started"));
setTimeout(fetchText, 2000);
diff --git a/apps/server/src/routes/api/ocr.ts b/apps/server/src/routes/api/ocr.ts
index 2b2b7a4658..9b20fa4940 100644
--- a/apps/server/src/routes/api/ocr.ts
+++ b/apps/server/src/routes/api/ocr.ts
@@ -305,6 +305,37 @@ async function getNoteOCRText(req: Request<{ noteId: string }>) {
} satisfies TextRepresentationResponse;
}
+async function getAttachmentOCRText(req: Request<{ attachmentId: string }>) {
+ const { attachmentId } = req.params;
+
+ const attachment = becca.getAttachment(attachmentId);
+ if (!attachment) {
+ return [404, { success: false, message: 'Attachment not found' }];
+ }
+
+ let ocrText: string | null = null;
+
+ if (attachment.blobId) {
+ const result = sql.getRow<{
+ textRepresentation: string | null;
+ }>(`
+ SELECT textRepresentation
+ FROM blobs
+ WHERE blobId = ?
+ `, [attachment.blobId]);
+
+ if (result) {
+ ocrText = result.textRepresentation;
+ }
+ }
+
+ return {
+ success: true,
+ text: ocrText || '',
+ hasOcr: !!ocrText
+ } satisfies TextRepresentationResponse;
+}
+
export default {
processNoteOCR,
processAttachmentOCR,
@@ -313,5 +344,6 @@ export default {
getBatchProgress,
getOCRStats,
deleteOCRResults,
- getNoteOCRText
+ getNoteOCRText,
+ getAttachmentOCRText
};
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 7e7e410399..b05c124f17 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -386,6 +386,7 @@ function register(app: express.Application) {
asyncApiRoute(GET, "/api/ocr/stats", ocrRoute.getOCRStats);
asyncApiRoute(DEL, "/api/ocr/delete/:blobId", ocrRoute.deleteOCRResults);
asyncApiRoute(GET, "/api/ocr/notes/:noteId/text", ocrRoute.getNoteOCRText);
+ asyncApiRoute(GET, "/api/ocr/attachments/:attachmentId/text", ocrRoute.getAttachmentOCRText);
app.use("", router);
}