Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(documents): remove OCR and index only Wiki-readable sources

muterC4cfdcecb5939
diff --git a/apps/desktop/scripts/build-native-runtime.mjs b/apps/desktop/scripts/build-native-runtime.mjs
index 847ed109..278ef2ee 100644
--- a/apps/desktop/scripts/build-native-runtime.mjs
+++ b/apps/desktop/scripts/build-native-runtime.mjs
@@ -79,19 +79,12 @@ const PLATFORMS = {
// Packages the services load at runtime by a name esbuild cannot see:
// createRequire, require.resolve of data files, or a native binding.
-const RUNTIME_PACKAGES = [
- "@livekit/local-inference",
- "@tesseract.js-data/chi_sim",
- "@tesseract.js-data/eng",
- "tesseract.js-core",
- "word-extractor",
-];
+const RUNTIME_PACKAGES = ["@livekit/local-inference", "word-extractor"];
// Packages that are model data rather than code: the installer leaves them
// out and Node Services downloads them when a feature first needs them
// (apps/node-services/src/model-packages.ts). Local models install
// separately as before.
export const MODEL_PACKAGE_GROUPS = [
- [/^@tesseract\.js-data\//, "ocr"],
// Silero VAD and the turn detector, embedded in the binding.
[/^@livekit\/local-inference-/, "voice"],
];
diff --git a/apps/desktop/scripts/bundle-node-services.mjs b/apps/desktop/scripts/bundle-node-services.mjs
index e6ef8d9a..ba98a415 100644
--- a/apps/desktop/scripts/bundle-node-services.mjs
+++ b/apps/desktop/scripts/bundle-node-services.mjs
@@ -25,9 +25,6 @@ export const NODE_SERVICES_EXTERNALS = [
"sharp",
"@img/*",
"pdfjs-dist",
- "tesseract.js",
- "tesseract.js-core",
- "@tesseract.js-data/*",
"jsdom",
// Loads file-type, pdfjs-dist and its parsers by name at runtime.
"officeparser",
diff --git a/apps/node-services/AGENTS.md b/apps/node-services/AGENTS.md
index fd2ce77a..18066fcf 100644
--- a/apps/node-services/AGENTS.md
+++ b/apps/node-services/AGENTS.md
@@ -49,7 +49,7 @@
desktop's offline runtime bundles each entry into one file
(`apps/desktop/scripts/bundle-node-services.mjs`), where every module shares
the entry's URL and relative paths resolve against the directory it runs in.
-- Packages that hold model data (OCR language data, the Voice VAD binding)
+- Packages that hold model data (the Voice VAD binding)
resolve through `src/model-packages.ts`: from node_modules in development
and images, downloaded on first use where the offline runtime lists them in
`models.json`. The `voice` role starts its download when the role starts,
diff --git a/apps/node-services/package.json b/apps/node-services/package.json
index 893fdf8f..d781c96a 100644
--- a/apps/node-services/package.json
+++ b/apps/node-services/package.json
@@ -32,15 +32,12 @@
"dependencies": {
"@hocuspocus/server": "^4.3.0",
"@hono/node-server": "^1.19.14",
- "@napi-rs/canvas": "1.0.5",
"@linger/document-files": "workspace:*",
"@linger/document-model": "workspace:*",
"@linger/knowledge-format": "workspace:*",
"@linger/service-kit": "workspace:*",
"@linger/voice-runtime": "workspace:*",
"@linger/wire-contracts": "workspace:*",
- "@tesseract.js-data/chi_sim": "1.0.0",
- "@tesseract.js-data/eng": "1.0.0",
"ajv": "8.17.1",
"hono": "^4.12.31",
"jsdom": "29.1.1",
@@ -51,8 +48,6 @@
"pdfjs-dist": "6.2.108",
"postgres": "3.4.9",
"proper-lockfile": "^4.1.2",
- "sharp": "0.35.3",
- "tesseract.js-core": "7.0.0",
"undici": "8.10.0",
"word-extractor": "1.0.4",
"ws": "8.22.0",
diff --git a/apps/node-services/src/document-normalizer/document-image-extract.ts b/apps/node-services/src/document-normalizer/document-image-extract.ts
deleted file mode 100644
index 9a074a3c..00000000
--- a/apps/node-services/src/document-normalizer/document-image-extract.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-import { DocumentOcr } from "./document-ocr.js";
-import {
- DocumentNormalizationError,
- MAX_DOCUMENT_PAGES,
- MAX_OCR_PIXELS,
-} from "./document-normalizer.js";
-import { decodeXmlEntities } from "./document-office-extract.js";
-
-export function svgToMarkdown(xml: string, filename?: string): string {
- if (!/<svg\b/iu.test(xml)) {
- throw new DocumentNormalizationError("DOCUMENT_SOURCE_INVALID");
- }
- const heading = imageHeading(filename, "SVG");
- const pieces: string[] = [];
- for (const tag of ["title", "desc", "text"] as const) {
- const pattern = new RegExp(`<${tag}\\b[^>]*>([\\s\\S]*?)</${tag}>`, "giu");
- for (const match of xml.matchAll(pattern)) {
- const text = decodeXmlEntities(stripTags(match[1] ?? ""))
- .replace(/[ \t]+\n/gu, "\n")
- .replace(/\n{3,}/gu, "\n\n")
- .trim();
- if (text) pieces.push(text);
- }
- }
- if (pieces.length > 0) {
- return `# ${heading}\n\n${pieces.join("\n\n")}`;
- }
- return `# ${heading}\n\n- Format: SVG`;
-}
-
-function imageHeading(filename: string | undefined, fallback: string): string {
- const base = filename?.split(/[/\\]/u).at(-1)?.trim();
- return (base && base.length > 0 ? base : fallback).replaceAll("\n", " ");
-}
-
-function stripTags(value: string): string {
- return value.replace(/<[^>]+>/gu, " ").replace(/[ \t]{2,}/gu, " ");
-}
-
-export async function rasterImageToMarkdown(
- source: Uint8Array,
- filename?: string,
-): Promise<string> {
- const ocr = new DocumentOcr();
- // One sparse-layout retry per empty page stays inside the worker deadline.
- const recognize = async (png: Uint8Array): Promise<string> =>
- (await ocr.recognize(png)) || ocr.recognize(png, "11");
- try {
- let format: string;
- const results: string[] = [];
- // Sharp handles bounded decoding and all TIFF pages; Skia handles BMP.
- if (source[0] === 0x42 && source[1] === 0x4d) {
- format = "BMP";
- if (source.byteLength < 26) {
- throw new DocumentNormalizationError("DOCUMENT_SOURCE_INVALID");
- }
- const header = new DataView(
- source.buffer,
- source.byteOffset,
- source.byteLength,
- );
- const coreHeader = header.getUint32(14, true) === 12;
- const width = coreHeader
- ? header.getUint16(18, true)
- : header.getInt32(18, true);
- const height = coreHeader
- ? header.getUint16(20, true)
- : Math.abs(header.getInt32(22, true));
- if (width <= 0 || height <= 0) {
- throw new DocumentNormalizationError("DOCUMENT_SOURCE_INVALID");
- }
- if (width * height > MAX_OCR_PIXELS) {
- throw new DocumentNormalizationError("DOCUMENT_SOURCE_TOO_LARGE");
- }
- const { createCanvas, loadImage } = await import("@napi-rs/canvas");
- const image = await loadImage(Buffer.from(source));
- if (image.width * image.height > MAX_OCR_PIXELS) {
- throw new DocumentNormalizationError("DOCUMENT_SOURCE_TOO_LARGE");
- }
- const canvas = createCanvas(image.width, image.height);
- try {
- canvas.getContext("2d").drawImage(image, 0, 0);
- results.push(await recognize(await canvas.encode("png")));
- } finally {
- canvas.width = canvas.height = 1;
- }
- } else {
- const { default: sharp } = await import("sharp");
- const metadata = await sharp(source, {
- limitInputPixels: MAX_OCR_PIXELS,
- }).metadata();
- format = metadata.format.toUpperCase();
- const pages = metadata.pages ?? 1;
- if (
- pages > MAX_DOCUMENT_PAGES ||
- (metadata.width ?? 0) * (metadata.pageHeight ?? metadata.height ?? 0) >
- MAX_OCR_PIXELS
- ) {
- throw new DocumentNormalizationError("DOCUMENT_SOURCE_TOO_LARGE");
- }
- for (let page = 0; page < pages; page++) {
- const png = await sharp(source, {
- page,
- pages: 1,
- limitInputPixels: MAX_OCR_PIXELS,
- })
- .rotate()
- .flatten({ background: "white" })
- .png()
- .toBuffer();
- results.push(await recognize(png));
- }
- }
- const text = results.filter(Boolean).join("\n\n");
- // A valid image without readable text is still a processed source, like
- // a text-less SVG; it must not block the documents around it.
- return text || `# ${imageHeading(filename, format)}\n\n- Format: ${format}`;
- } catch (error) {
- if (error instanceof DocumentNormalizationError) throw error;
- throw new DocumentNormalizationError("DOCUMENT_SOURCE_INVALID");
- } finally {
- ocr.dispose();
- }
-}
diff --git a/apps/node-services/src/document-normalizer/document-normalizer-core.ts b/apps/node-services/src/document-normalizer/document-normalizer-core.ts
index d543adfd..e602f9f3 100644
--- a/apps/node-services/src/document-normalizer/document-normalizer-core.ts
+++ b/apps/node-services/src/document-normalizer/document-normalizer-core.ts
@@ -83,16 +83,11 @@ export async function normalizeDocumentContent(
markdown = await extractGzipMarkdown(input);
break;
case "svg":
- markdown = (await import("./document-image-extract.js")).svgToMarkdown(
+ markdown = (await import("./document-svg-extract.js")).svgToMarkdown(
decodeUtf8Text(input.source),
input.filename,
);
break;
- case "image":
- markdown = await (
- await import("./document-image-extract.js")
- ).rasterImageToMarkdown(input.source, input.filename);
- break;
case "html":
markdown = htmlToMarkdown(decodeUtf8Text(input.source));
break;
diff --git a/apps/node-services/src/document-normalizer/document-normalizer.ts b/apps/node-services/src/document-normalizer/document-normalizer.ts
index d0e64f97..a1ccf545 100644
--- a/apps/node-services/src/document-normalizer/document-normalizer.ts
+++ b/apps/node-services/src/document-normalizer/document-normalizer.ts
@@ -1,15 +1,9 @@
import { Worker } from "node:worker_threads";
-import {
- installModelPackages,
- modelPackageNames,
- modelPackagesInstalled,
-} from "../model-packages.js";
import { serviceModule } from "../paths.js";
export const DOCUMENT_NORMALIZER_NAME = "llm-wiki-document-markdown";
export const DOCUMENT_NORMALIZER_VERSION = "2";
-export const MAX_OCR_PIXELS = 16_000_000;
export const MAX_DOCUMENT_PAGES = 100;
export const MAX_DOCUMENT_SOURCE_BYTES = 50 * 1024 * 1024;
export const MAX_DOCUMENT_MARKDOWN_BYTES = 32 * 1024 * 1024;
@@ -160,26 +154,20 @@ type DocumentNormalizationExecutor = (
interface WorkerDocumentNormalizerOptions {
execute?: DocumentNormalizationExecutor;
- /** OCR's language data, when the runtime ships it separately. */
- installModels?: () => Promise<void>;
maxAdmittedBytes?: number;
maxQueued?: number;
- /** A failed model install; conversions that need OCR fail as unavailable. */
- onModelsUnavailable?: (error: unknown) => void;
timeoutMs?: number;
}
/**
* The process's one normalizer. Text formats convert in process; the rest
- * convert in an isolated worker, one at a time, because OCR memory (WASM,
- * canvas and image decoding) sits outside the worker heap limit. A request
+ * convert in an isolated worker, one at a time, so a PDF, Office or archive
+ * parser that exhausts memory or hangs is stopped without the process. A request
* waits for the worker at most one timeout and fails as unavailable; the
* conversion itself then has its own timeout, which is terminal.
*/
export class WorkerDocumentNormalizer implements DocumentNormalizer {
readonly #execute: DocumentNormalizationExecutor;
- readonly #installModels: () => Promise<void>;
- readonly #onModelsUnavailable: (error: unknown) => void;
readonly #maxAdmittedBytes: number;
readonly #maxQueued: number;
readonly #timeoutMs: number;
@@ -189,8 +177,6 @@ export class WorkerDocumentNormalizer implements DocumentNormalizer {
constructor(options: WorkerDocumentNormalizerOptions = {}) {
this.#execute = options.execute ?? executeInWorker;
- this.#installModels = options.installModels ?? installOcrModels;
- this.#onModelsUnavailable = options.onModelsUnavailable ?? (() => {});
this.#maxQueued = options.maxQueued ?? MAX_QUEUED_DOCUMENT_NORMALIZATIONS;
this.#timeoutMs =
options.timeoutMs ?? DEFAULT_DOCUMENT_NORMALIZATION_TIMEOUT_MS;
@@ -229,8 +215,6 @@ export class WorkerDocumentNormalizer implements DocumentNormalizer {
if (core.isInProcessDocumentSource(request)) {
return await core.normalizeDocumentContent(request);
}
- // Outside the conversion's deadline: the first install downloads.
- await this.#installModels().catch(this.#onModelsUnavailable);
const release = await this.#acquireWorker(signal);
try {
return await this.#convert(request, signal);
@@ -311,11 +295,6 @@ export class WorkerDocumentNormalizer implements DocumentNormalizer {
}
}
-async function installOcrModels(): Promise<void> {
- const names = modelPackageNames("ocr");
- if (!modelPackagesInstalled(names)) await installModelPackages(names);
-}
-
function unavailable(): DocumentNormalizationError {
return new DocumentNormalizationError("DOCUMENT_NORMALIZATION_UNAVAILABLE");
}
diff --git a/apps/node-services/src/document-normalizer/document-ocr.ts b/apps/node-services/src/document-normalizer/document-ocr.ts
deleted file mode 100644
index 8b3d9052..00000000
--- a/apps/node-services/src/document-normalizer/document-ocr.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { readFile } from "node:fs/promises";
-import { createRequire } from "node:module";
-import path from "node:path";
-import { gunzipSync } from "node:zlib";
-
-import { modelPackageDirectory } from "../model-packages.js";
-import { DocumentNormalizationError } from "./document-normalizer.js";
-
-const require = createRequire(import.meta.url);
-
-interface TessApi {
- Init(path: null, languages: string, engine: number): number;
- SetVariable(name: string, value: string): boolean;
- SetImageFile(orientation: number, angle: number): number;
- Recognize(monitor: null): number;
- GetUTF8Text(): string;
- End(): void;
-}
-
-interface TessCore {
- FS: {
- writeFile(path: string, bytes: Uint8Array): void;
- unlink(path: string): void;
- };
- TessBaseAPI: new () => TessApi;
- destroy(api: TessApi): void;
-}
-
-// Tesseract inserts spaces inside Chinese words. Keep line boundaries and Latin
-// word spacing, but restore contiguous Han terms for exact search.
-export function joinOcrHanRuns(text: string): string {
- return text.replace(/(\p{Script=Han})[ \t]+(?=\p{Script=Han})/gu, "$1");
-}
-
-// Run WASM in the normalizer's existing worker, so its hard deadline also stops
-// OCR. No nested workers or host executable is needed. The language data comes
-// from node_modules, or from the model packages the normalizer installs before
-// it starts the worker when the runtime ships without them.
-export class DocumentOcr {
- #core?: TessCore;
- #api?: TessApi;
-
- // Page segmentation mode 3 reads documents in layout order; 11 finds sparse
- // labels in screenshots where mode 3 sees no text block.
- async recognize(
- png: Uint8Array,
- pageSegMode: "3" | "11" = "3",
- ): Promise<string> {
- if (!this.#core || !this.#api) await this.#initialize();
- const core = this.#core!;
- const api = this.#api!;
- api.SetVariable("tessedit_pageseg_mode", pageSegMode);
- core.FS.writeFile("/input", png);
- try {
- if (api.SetImageFile(1, 0) !== 0 || api.Recognize(null) !== 0) {
- throw new DocumentNormalizationError("DOCUMENT_SOURCE_INVALID");
- }
- return joinOcrHanRuns(api.GetUTF8Text()).trim();
- } finally {
- core.FS.unlink("/input");
- }
- }
-
- dispose(): void {
- if (this.#api) {
- this.#api.End();
- this.#core!.destroy(this.#api);
- }
- this.#api = undefined;
- this.#core = undefined;
- }
-
- async #initialize(): Promise<void> {
- try {
- const createCore =
- require("tesseract.js-core/tesseract-core-lstm.js") as (options: {
- print: () => void;
- printErr: () => void;
- }) => Promise<TessCore>;
- this.#core = await createCore({ print: () => {}, printErr: () => {} });
- for (const language of ["eng", "chi_sim"]) {
- const data = `@tesseract.js-data/${language}`;
- const file = `4.0.0_best_int/${language}.traineddata.gz`;
- const directory = modelPackageDirectory(data);
- const model = await readFile(
- directory
- ? path.join(directory, file)
- : require.resolve(`${data}/${file}`),
- );
- this.#core.FS.writeFile(`${language}.traineddata`, gunzipSync(model));
- }
- this.#api = new this.#core.TessBaseAPI();
- if (this.#api.Init(null, "eng+chi_sim", 1) !== 0)
- throw new Error("OCR init");
- } catch {
- this.dispose();
- throw new DocumentNormalizationError(
- "DOCUMENT_NORMALIZATION_UNAVAILABLE",
- );
- }
- }
-}
diff --git a/apps/node-services/src/document-normalizer/document-pdf-extract.ts b/apps/node-services/src/document-normalizer/document-pdf-extract.ts
index 00737866..aebb1d59 100644
--- a/apps/node-services/src/document-normalizer/document-pdf-extract.ts
+++ b/apps/node-services/src/document-normalizer/document-pdf-extract.ts
@@ -1,24 +1,13 @@
import { fileURLToPath } from "node:url";
-import { createCanvas } from "@napi-rs/canvas";
-import { getDocument, OPS } from "pdfjs-dist/legacy/build/pdf.mjs";
+import { getDocument } from "pdfjs-dist/legacy/build/pdf.mjs";
import {
DocumentNormalizationError,
- MAX_OCR_PIXELS,
MAX_DOCUMENT_PAGES,
} from "./document-normalizer.js";
-import { DocumentOcr } from "./document-ocr.js";
const PDFJS_MODULE_URL = import.meta.resolve("pdfjs-dist/legacy/build/pdf.mjs");
-const IMAGE_OPERATORS = new Set<number>([
- OPS.paintImageXObject,
- OPS.paintInlineImageXObject,
- OPS.paintImageXObjectRepeat,
- OPS.paintInlineImageXObjectGroup,
- OPS.paintImageMaskXObject,
- OPS.paintImageMaskXObjectRepeat,
-]);
export async function extractPdfMarkdown(source: Uint8Array): Promise<string> {
if (!Buffer.from(source.subarray(0, 1024)).includes(Buffer.from("%PDF-"))) {
@@ -35,9 +24,7 @@ export async function extractPdfMarkdown(source: Uint8Array): Promise<string> {
disableFontFace: true,
useSystemFonts: false,
stopAtErrors: true,
- maxImageSize: MAX_OCR_PIXELS,
});
- const ocr = new DocumentOcr();
try {
const document = await loading.promise;
if (document.numPages > MAX_DOCUMENT_PAGES) {
@@ -55,34 +42,7 @@ export async function extractPdfMarkdown(source: Uint8Array): Promise<string> {
.join("")
.replace(/ +\n/g, "\n")
.trim();
- const operators = await page.getOperatorList();
- if (
- !operators.fnArray.some((operator) => IMAGE_OPERATORS.has(operator))
- ) {
- pages.push(native);
- continue;
- }
- const viewport = page.getViewport({ scale: 200 / 72 });
- const width = Math.ceil(viewport.width);
- const height = Math.ceil(viewport.height);
- if (width * height > MAX_OCR_PIXELS) {
- throw new DocumentNormalizationError("DOCUMENT_SOURCE_TOO_LARGE");
- }
- const canvas = createCanvas(width, height);
- try {
- await page.render({ canvas: canvas as never, viewport }).promise;
- const recognized = await ocr.recognize(await canvas.encode("png"));
- // Keep exact text-layer spelling; do not discard scanned regions on mixed pages.
- const nativeLines = new Set(native.split("\n").map(compact));
- const extra = recognized
- .split("\n")
- .filter((line) => !nativeLines.has(compact(line)))
- .join("\n")
- .trim();
- pages.push([native, extra].filter(Boolean).join("\n\n"));
- } finally {
- canvas.width = canvas.height = 1;
- }
+ pages.push(native);
} finally {
page.cleanup();
}
@@ -92,11 +52,6 @@ export async function extractPdfMarkdown(source: Uint8Array): Promise<string> {
if (error instanceof DocumentNormalizationError) throw error;
throw new DocumentNormalizationError("DOCUMENT_SOURCE_INVALID");
} finally {
- ocr.dispose();
await loading.destroy().catch(() => undefined);
}
}
-
-function compact(value: string): string {
- return value.replace(/\s+/gu, "");
-}
diff --git a/apps/node-services/src/document-normalizer/document-source-kind.ts b/apps/node-services/src/document-normalizer/document-source-kind.ts
index a6116692..eedfd4d6 100644
--- a/apps/node-services/src/document-normalizer/document-source-kind.ts
+++ b/apps/node-services/src/document-normalizer/document-source-kind.ts
@@ -26,7 +26,6 @@ export type DocumentSourceKind =
| "zip"
| "gzip"
| "svg"
- | "image"
| "unsupported";
const IN_PROCESS_DOCUMENT_SOURCE_KINDS = new Set<DocumentSourceKind>([
@@ -138,25 +137,25 @@ const EXTENSION_KINDS: Record<string, DocumentSourceKind> = {
c: "code",
cpp: "code",
css: "code",
- avif: "image",
- bmp: "image",
+ avif: "unsupported",
+ bmp: "unsupported",
csv: "csv",
doc: "doc",
docx: "docx",
- gif: "image",
+ gif: "unsupported",
go: "code",
gz: "gzip",
gzip: "gzip",
h: "code",
- heic: "image",
- heif: "image",
+ heic: "unsupported",
+ heif: "unsupported",
hpp: "code",
htm: "html",
html: "html",
- ico: "image",
+ ico: "unsupported",
java: "code",
- jpeg: "image",
- jpg: "image",
+ jpeg: "unsupported",
+ jpg: "unsupported",
js: "code",
json: "json",
jsx: "code",
@@ -166,7 +165,7 @@ const EXTENSION_KINDS: Record<string, DocumentSourceKind> = {
md: "markdown",
mmd: "code",
pdf: "pdf",
- png: "image",
+ png: "unsupported",
pptx: "pptx",
py: "code",
rs: "code",
@@ -174,14 +173,14 @@ const EXTENSION_KINDS: Record<string, DocumentSourceKind> = {
sh: "code",
sql: "code",
svg: "svg",
- tif: "image",
- tiff: "image",
+ tif: "unsupported",
+ tiff: "unsupported",
toml: "code",
ts: "code",
tsv: "tsv",
tsx: "code",
txt: "plain",
- webp: "image",
+ webp: "unsupported",
xlsx: "xlsx",
xml: "xml",
yaml: "yaml",
@@ -199,7 +198,7 @@ const REPRESENTATION_KINDS: Record<string, DocumentSourceKind> = {
markdown: "markdown",
pdf: "pdf",
plain_text: "plain",
- png: "image",
+ png: "unsupported",
pptx: "pptx",
svg: "svg",
tsv: "tsv",
@@ -282,8 +281,8 @@ function kindFromMediaType(essence: string): DocumentSourceKind | undefined {
if (!essence || essence === "application/octet-stream") return undefined;
const mapped = MEDIA_TYPE_KINDS[essence];
if (mapped) return mapped;
- if (essence.startsWith("image/")) return "image";
if (
+ essence.startsWith("image/") ||
essence.startsWith("audio/") ||
essence.startsWith("video/") ||
EXPLICITLY_UNSUPPORTED_MEDIA_TYPES.has(essence)
diff --git a/apps/node-services/src/document-normalizer/document-svg-extract.ts b/apps/node-services/src/document-normalizer/document-svg-extract.ts
new file mode 100644
index 00000000..463dc1e1
--- /dev/null
+++ b/apps/node-services/src/document-normalizer/document-svg-extract.ts
@@ -0,0 +1,33 @@
+import { DocumentNormalizationError } from "./document-normalizer.js";
+import { decodeXmlEntities } from "./document-office-extract.js";
+
+export function svgToMarkdown(xml: string, filename?: string): string {
+ if (!/<svg\b/iu.test(xml)) {
+ throw new DocumentNormalizationError("DOCUMENT_SOURCE_INVALID");
+ }
+ const heading = imageHeading(filename, "SVG");
+ const pieces: string[] = [];
+ for (const tag of ["title", "desc", "text"] as const) {
+ const pattern = new RegExp(`<${tag}\\b[^>]*>([\\s\\S]*?)</${tag}>`, "giu");
+ for (const match of xml.matchAll(pattern)) {
+ const text = decodeXmlEntities(stripTags(match[1] ?? ""))
+ .replace(/[ \t]+\n/gu, "\n")
+ .replace(/\n{3,}/gu, "\n\n")
+ .trim();
+ if (text) pieces.push(text);
+ }
+ }
+ if (pieces.length > 0) {
+ return `# ${heading}\n\n${pieces.join("\n\n")}`;
+ }
+ return `# ${heading}\n\n- Format: SVG`;
+}
+
+function imageHeading(filename: string | undefined, fallback: string): string {
+ const base = filename?.split(/[/\\]/u).at(-1)?.trim();
+ return (base && base.length > 0 ? base : fallback).replaceAll("\n", " ");
+}
+
+function stripTags(value: string): string {
+ return value.replace(/<[^>]+>/gu, " ").replace(/[ \t]{2,}/gu, " ");
+}
diff --git a/apps/node-services/src/main.ts b/apps/node-services/src/main.ts
index 9f470823..cef10d29 100644
--- a/apps/node-services/src/main.ts
+++ b/apps/node-services/src/main.ts
@@ -150,12 +150,7 @@ export async function main(
const http = selected.some((name) => HTTP_ROLES.has(name))
? await startHttpHost(readHttpAddress(process.env))
: undefined;
- const normalizer = new WorkerDocumentNormalizer({
- onModelsUnavailable: (error) =>
- logger.log("warn", "document_normalizer.models_unavailable", {
- error,
- }),
- });
+ const normalizer = new WorkerDocumentNormalizer();
const seams: RoleHost["seams"] = {};
const running: { name: RoleName; role: RunningRole }[] = [];
const stopRoles = async (): Promise<void> => {
diff --git a/apps/node-services/src/memory/README.md b/apps/node-services/src/memory/README.md
index 55426f0e..747d4cc0 100644
--- a/apps/node-services/src/memory/README.md
+++ b/apps/node-services/src/memory/README.md
@@ -368,8 +368,10 @@ because it is also in My Pages. On the next reconciliation My Pages deletes sour
list, cascading their versions, chunks and Session facts; a new version replaces only that source's chunks. The Daily/Weekly reports are derived
summaries, indexed as their own `period_summary` sources and never as Raw again. When a current safe Wiki page
references an exact historical Version of a Document, that Version enters Raw/Chunk ahead of the Document's current
-head, so a Wiki reference never points at the uploaded original while the Chunk indexes a later export. Archives and
-audio or video without a transcript do not enter the index.
+head, so a Wiki reference never points at the uploaded original while the Chunk indexes a later export. My Pages
+and imported mail enter only when the Wiki whitelist would admit them (TeamHub's `source_rejection_reason` is empty):
+images, scanned PDFs, spreadsheets, data, log and code files, archives, and audio or video stay out of the index,
+because the Wiki never records them.
Memory does not normalize Documents: it reads My pages and imported mail as the Markdown TeamHub stored in
`document_texts` (one River job per version), through `memory_source.personal_documents` and, for
Documents whose indexed hash differs, `personal_document_markdown`. A My pages Document is dated by its Version; an
@@ -377,17 +379,15 @@ imported mail message by the send time in its `- Timestamp:` header and named by
stores every message at the time of the import (the Version time and file name are used only when the header has no
readable time or subject). The normalizer TeamHub's job calls is
`apps/node-services/src/document-normalizer`, served by LLM Wiki in a restricted worker thread of this process. It
-converts PDF, DOC/DOCX, PPTX, XLSX, ODT/ODS/ODP, EPUB, EML/MHTML, Office templates and images into canonical Markdown.
-Scanned PDFs and raster images use the Chinese and English OCR bundled with the dependencies; conversion needs no
-network, Docling, system OCR, LibreOffice, extra API key or separate service. After installing the repository's locked
-dependencies, `pnpm dev` uses this path; CI and the production image carry the same parsers, WASM and language models.
+converts PDF, DOC/DOCX, PPTX, XLSX, ODT/ODS/ODP, EPUB, EML/MHTML, Office templates and SVG into canonical Markdown.
+There is no OCR: a PDF gives only its text layer, so a scanned PDF has no text, and raster images are unsupported.
+Conversion needs no network, Docling, LibreOffice, extra API key or separate service. After installing the
+repository's locked dependencies, `pnpm dev` uses this path; CI and the production image carry the same parsers.
The index excludes generic ZIP/gzip, audio/video and legacy XLS/PPT through `document_wiki_source_heads`, without mistaking ZIP-based Office/EPUB for archives.
There are no backends for macro-enabled Office (PPTM/XLSM/XLTM), Box Notes, Outlook MSG, Apple Pages, AFP/EBCDIC or
DocLang. AsciiDoc and LaTeX uploaded as UTF-8 `text/*` can be read as text but have no dedicated parser; `.adoc` with
-`application/octet-stream` and `.tex` with `application/x-tex` are refused. Local OCR may still return no text for a
-skewed scanned page, and complex layouts and scan quality need their own acceptance. A raster image with no
-recognized text is retried once with the sparse-text layout; with still no text it yields only the file name heading
-and format line, without reporting an empty source.
+`application/octet-stream` and `.tex` with `application/x-tex` are refused. Complex PDF layouts need their own
+acceptance.
A version the normalizer cannot read has no ready text in TeamHub and is simply not indexed; Memory keeps no failure record of its own, and the next version is indexed once its text is ready.
Markdown is split into Chunks by heading level and paragraph boundaries; consecutive timestamped turns merge into a
conversation Chunk with context, so one sentence never takes a whole result. Ordinary blocks do not overlap; only
diff --git a/apps/node-services/src/model-packages.ts b/apps/node-services/src/model-packages.ts
index 3ddadae1..7fbd3bb7 100644
--- a/apps/node-services/src/model-packages.ts
+++ b/apps/node-services/src/model-packages.ts
@@ -13,7 +13,7 @@ import { mirrorHome, packageRoot } from "./paths.js";
// the images, they come from node_modules like any other package.
export const MODEL_PACKAGES_FILE = "models.json";
-export type ModelPackageGroup = "ocr" | "voice";
+export type ModelPackageGroup = "voice";
export interface ModelPackage {
group: ModelPackageGroup;
diff --git a/apps/node-services/tests/document-normalizer/document-local-formats.test.ts b/apps/node-services/tests/document-normalizer/document-local-formats.test.ts
index a06788d4..2141fa3e 100644
--- a/apps/node-services/tests/document-normalizer/document-local-formats.test.ts
+++ b/apps/node-services/tests/document-normalizer/document-local-formats.test.ts
@@ -1,6 +1,5 @@
import { readFile } from "node:fs/promises";
-import sharp from "sharp";
import JSZip from "jszip";
import { describe, expect, it } from "vitest";
@@ -24,11 +23,11 @@ async function convert(name: string, source?: Uint8Array): Promise<string> {
);
}
-describe("local document extraction with bundled models", () => {
+describe("local document extraction", () => {
it.each(manifest)(
"extracts the body of $name",
async (fixture) => {
- if (fixture.name === "blank.pdf") {
+ if (fixture.facts.length === 0) {
await expect(convert(fixture.name)).rejects.toMatchObject({
code: "DOCUMENT_SOURCE_EMPTY",
});
@@ -60,68 +59,6 @@ describe("local document extraction with bundled models", () => {
expect(await convert("structured.pptx")).toContain("SPEAKER-NOTE");
});
- it("decodes JPEG, WebP, GIF, AVIF, BMP and both pages of a TIFF locally", async () => {
- const english = await readFile(new URL("ocr-en.png", fixtures));
- for (const format of ["jpeg", "webp", "gif", "avif"] as const) {
- const source = await sharp(english).toFormat(format).toBuffer();
- const result = await normalizeDocumentContent({
- filename: `scan.${format}`,
- mediaType: `image/${format}`,
- source,
- });
- expect(new TextDecoder().decode(result)).toContain("9876");
- }
- const { data, info } = await sharp(english)
- .removeAlpha()
- .raw()
- .toBuffer({ resolveWithObject: true });
- const stride = Math.ceil((info.width * 3) / 4) * 4;
- const bitmap = Buffer.alloc(54 + stride * info.height);
- bitmap.write("BM");
- bitmap.writeUInt32LE(bitmap.length, 2);
- bitmap.writeUInt32LE(54, 10);
- bitmap.writeUInt32LE(40, 14);
- bitmap.writeInt32LE(info.width, 18);
- bitmap.writeInt32LE(info.height, 22);
- bitmap.writeUInt16LE(1, 26);
- bitmap.writeUInt16LE(24, 28);
- for (let y = 0; y < info.height; y++)
- for (let x = 0; x < info.width; x++) {
- const input = (y * info.width + x) * 3;
- const output = 54 + (info.height - y - 1) * stride + x * 3;
- bitmap[output] = data[input + 2]!;
- bitmap[output + 1] = data[input + 1]!;
- bitmap[output + 2] = data[input]!;
- }
- const bitmapText = await normalizeDocumentContent({
- filename: "scan.bmp",
- mediaType: "image/bmp",
- source: bitmap,
- });
- expect(new TextDecoder().decode(bitmapText)).toContain("9876");
- const sparse = await readFile(new URL("ocr-sparse.png", fixtures));
- const size = await sharp(english).metadata();
- const frame = await sharp(sparse)
- .resize(size.width, size.height, {
- fit: "contain",
- background: "white",
- })
- .toBuffer();
- const tiff = await sharp([english, frame], { join: { animated: true } })
- .tiff()
- .toBuffer();
- const result = new TextDecoder().decode(
- await normalizeDocumentContent({
- filename: "scans.tiff",
- mediaType: "image/tiff",
- source: tiff,
- }),
- );
- expect(compact(result)).toContain("SCAN-ORCHID");
- // The resized sparse frame comes back with mixed letter case.
- expect(compact(result).toLowerCase()).toContain("sparse9876");
- }, 30_000);
-
it.each([
"sample.odt",
"sample.ods",
@@ -190,21 +127,6 @@ describe("local document extraction with bundled models", () => {
).rejects.toMatchObject({ code: "DOCUMENT_SOURCE_INVALID" });
});
- it("rejects an oversized bitmap before allocating decoded pixels", async () => {
- const source = Buffer.alloc(54);
- source.write("BM");
- source.writeUInt32LE(40, 14);
- source.writeInt32LE(100_000, 18);
- source.writeInt32LE(100_000, 22);
- await expect(
- normalizeDocumentContent({
- filename: "huge.bmp",
- mediaType: "image/bmp",
- source,
- }),
- ).rejects.toMatchObject({ code: "DOCUMENT_SOURCE_TOO_LARGE" });
- });
-
it("decodes MIME transfer encoding and an encoded subject", async () => {
const source = Buffer.from(
[
diff --git a/apps/node-services/tests/document-normalizer/document-normalizer.test.ts b/apps/node-services/tests/document-normalizer/document-normalizer.test.ts
index e511790c..7724d4b0 100644
--- a/apps/node-services/tests/document-normalizer/document-normalizer.test.ts
+++ b/apps/node-services/tests/document-normalizer/document-normalizer.test.ts
@@ -123,7 +123,7 @@ describe("document normalization", () => {
);
});
- it("extracts archive and SVG text without indexing image metadata as body", async () => {
+ it("extracts archive and SVG text and reads no raster image", async () => {
await expect(
normalizeDocumentContent({
filename: "bundle.zip",
@@ -137,9 +137,7 @@ describe("document normalization", () => {
},
]),
}).then(decode),
- ).resolves.toBe(
- "## notes.md\n\n# From zip\n\n## photo.png\n\n# photo.png\n\n- Format: PNG\n",
- );
+ ).resolves.toBe("## notes.md\n\n# From zip\n");
await expect(
normalizeDocumentContent({
@@ -157,29 +155,15 @@ describe("document normalization", () => {
}).then(decode),
).resolves.toBe("# icon.svg\n\nIcon\n\nHello wiki\n");
- await expect(
- normalizeDocumentContent({
- filename: "photo.png",
- mediaType: PNG_MEDIA_TYPE,
- source: pngFixture(),
- }).then(decode),
- ).resolves.toBe("# photo.png\n\n- Format: PNG\n");
-
- await expect(
- normalizeDocumentContent({
- filename: "photo.png",
- mediaType: PNG_MEDIA_TYPE,
- source: pngFixture().subarray(0, 24),
- }),
- ).rejects.toMatchObject({ code: "DOCUMENT_SOURCE_INVALID" });
-
- await expect(
- normalizeDocumentContent({
- filename: "photo.heic",
- mediaType: "image/heic",
- source: encode("not a real heic"),
- }).then(decode),
- ).rejects.toMatchObject({ code: "DOCUMENT_SOURCE_INVALID" });
+ for (const [filename, mediaType] of [
+ ["photo.png", PNG_MEDIA_TYPE],
+ ["photo.heic", "image/heic"],
+ ["photo.jpg", "application/octet-stream"],
+ ] as const) {
+ await expect(
+ normalizeDocumentContent({ filename, mediaType, source: pngFixture() }),
+ ).rejects.toMatchObject({ code: "DOCUMENT_SOURCE_UNSUPPORTED" });
+ }
});
it("rejects nested gzip instead of recursing through wrappers", async () => {
@@ -245,7 +229,7 @@ describe("document normalization", () => {
);
});
- it("keeps SVG in-process and sends ZIP and raster images to the worker path", () => {
+ it("keeps SVG in-process and sends ZIP to the worker path", () => {
expect(
isInProcessDocumentSource({
filename: "icon.svg",
@@ -258,12 +242,6 @@ describe("document normalization", () => {
mediaType: ZIP_MEDIA_TYPE,
}),
).toBe(false);
- expect(
- isInProcessDocumentSource({
- filename: "photo.png",
- mediaType: PNG_MEDIA_TYPE,
- }),
- ).toBe(false);
});
it("keeps UTF-8 Markdown and treats a generic .md Version as text", async () => {
diff --git a/apps/node-services/tests/document-normalizer/document-ocr.test.ts b/apps/node-services/tests/document-normalizer/document-ocr.test.ts
deleted file mode 100644
index 1372ffc3..00000000
--- a/apps/node-services/tests/document-normalizer/document-ocr.test.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { joinOcrHanRuns } from "../../src/document-normalizer/document-ocr.js";
-
-// Han text built from code points: the repair only applies to Han characters.
-const han = (...codePoints: number[]): string =>
- String.fromCodePoint(...codePoints);
-const project = han(0x6668, 0x661f, 0x9879, 0x76ee);
-const owner = han(0x5f20, 0x654f);
-
-describe("OCR Han spacing repair", () => {
- it("joins Han characters that OCR split with spaces", () => {
- expect(joinOcrHanRuns([...project].join(" \t "))).toBe(project);
- });
-
- it("keeps Latin word spacing, Han-Latin spacing and line breaks", () => {
- const text = `${[...project].join(" ")} SCAN ORCHID 9876\n${[...owner].join(" ")}`;
- expect(joinOcrHanRuns(text)).toBe(`${project} SCAN ORCHID 9876\n${owner}`);
- });
-});
diff --git a/apps/node-services/tests/document-normalizer/fixtures/local-documents/README.md b/apps/node-services/tests/document-normalizer/fixtures/local-documents/README.md
index 87a95c13..3c3bf6fc 100644
--- a/apps/node-services/tests/document-normalizer/fixtures/local-documents/README.md
+++ b/apps/node-services/tests/document-normalizer/fixtures/local-documents/README.md
@@ -5,14 +5,10 @@ facts that must survive; the tests separately check Office table column mapping,
notes and blank input.
- PDF: ReportLab text layers in Chinese and English, tables, two columns, a scanned page, text and a scanned area on
- one page, and a blank page.
-- Images: Chinese and English acceptance forms drawn with Pillow; the tests transcode these PNGs to JPEG, WebP, GIF,
- AVIF, BMP and multi-page TIFF. `ocr-sparse.png` is an interface-like screenshot drawn with `@napi-rs/canvas` (color
- blocks and one line of labels); the default layout finds nothing, and only the sparse-text layout reads the labels.
+ one page, and a blank page. Only text layers are read, so the scanned page and the blank page give no body.
- Office: tables, formatted cells and notes generated with python-docx, python-pptx and openpyxl.
- ODF, EPUB, EML, MHTML: minimal standard XML, ZIP and MIME documents; DOTX changes the main content type of a
synthetic DOCX.
-OCR uses the Chinese and English Tesseract models pinned in the dependencies; nothing is downloaded and no system OCR
-or LibreOffice is needed. The fixtures prove that file paths and body extraction work; they make no promise about
+Nothing is downloaded and no LibreOffice is needed. The fixtures prove that file paths and body extraction work; they make no promise about
two-column reading order, complex PDF tables, handwriting or low-quality scans.
diff --git a/apps/node-services/tests/document-normalizer/fixtures/local-documents/manifest.json b/apps/node-services/tests/document-normalizer/fixtures/local-documents/manifest.json
index e1fab1f1..d51fe9b0 100644
--- a/apps/node-services/tests/document-normalizer/fixtures/local-documents/manifest.json
+++ b/apps/node-services/tests/document-normalizer/fixtures/local-documents/manifest.json
@@ -46,32 +46,18 @@
"note": "Three exact project-owner-budget relationships must survive.",
"order": []
},
- {
- "name": "ocr-en.png",
- "mediaType": "image/png",
- "facts": ["SCAN-ORCHID", "9876", "Daniel Lee", "2026-12-01"],
- "note": "",
- "order": []
- },
- {
- "name": "ocr-sparse.png",
- "mediaType": "image/png",
- "facts": ["9876"],
- "note": "UI-like screenshot whose default page layout finds no text; sparse-text layout must recover the label.",
- "order": []
- },
{
"name": "scan-en.pdf",
"mediaType": "application/pdf",
- "facts": ["SCAN-ORCHID", "9876", "Daniel Lee", "2026-12-01"],
- "note": "",
+ "facts": [],
+ "note": "Negative control: a scanned page has no text layer and gives no body.",
"order": []
},
{
"name": "mixed.pdf",
"mediaType": "application/pdf",
- "facts": ["COVER-ALPHA", "SCAN-ORCHID", "9876", "Daniel Lee"],
- "note": "Same page has native text and a scanned region.",
+ "facts": ["COVER-ALPHA"],
+ "note": "Same page has native text and a scanned region; only the text layer is read.",
"order": []
},
{
@@ -93,7 +79,7 @@
"2400",
"Validate search"
],
- "note": "Embedded image OCR is tracked separately, not assumed for either converter.",
+ "note": "Embedded images give no text.",
"order": []
},
{
diff --git a/apps/node-services/tests/document-normalizer/fixtures/local-documents/ocr-en.png b/apps/node-services/tests/document-normalizer/fixtures/local-documents/ocr-en.png
deleted file mode 100644
index d264b6aa..00000000
Binary files a/apps/node-services/tests/document-normalizer/fixtures/local-documents/ocr-en.png and /dev/null differ
diff --git a/apps/node-services/tests/document-normalizer/fixtures/local-documents/ocr-sparse.png b/apps/node-services/tests/document-normalizer/fixtures/local-documents/ocr-sparse.png
deleted file mode 100644
index 1120507c..00000000
Binary files a/apps/node-services/tests/document-normalizer/fixtures/local-documents/ocr-sparse.png and /dev/null differ
diff --git a/apps/node-services/tests/model-packages.test.ts b/apps/node-services/tests/model-packages.test.ts
index 03b0f51b..f0f72abc 100644
--- a/apps/node-services/tests/model-packages.test.ts
+++ b/apps/node-services/tests/model-packages.test.ts
@@ -48,9 +48,9 @@ const integrity = (body: Buffer) =>
const root = mkdtempSync(path.join(os.tmpdir(), "model-packages-"));
afterAll(() => rm(root, { recursive: true, force: true }));
-const eng = tarball({
- "package/package.json": '{"name":"@tesseract.js-data/eng"}',
- "package/4.0.0_best_int/eng.traineddata.gz": "eng data",
+const turn = tarball({
+ "package/package.json": '{"name":"@livekit/local-inference-darwin-arm64"}',
+ "package/models/turn.onnx": "turn data",
});
const vad = tarball({ "package/index.node": "binding" });
let home: string;
@@ -65,13 +65,13 @@ beforeEach(async () => {
path.join(runtime.packageRoot, "models.json"),
JSON.stringify({
packages: {
- "@tesseract.js-data/eng": {
- group: "ocr",
- version: "1.0.0",
- integrity: integrity(eng),
+ "@livekit/local-inference-darwin-arm64": {
+ group: "voice",
+ version: "0.2.7",
+ integrity: integrity(turn),
tarballs: [
- "https://registry.example/eng-1.0.0.tgz",
- "https://mirror.example/eng-1.0.0.tgz",
+ "https://registry.example/turn-0.2.7.tgz",
+ "https://mirror.example/turn-0.2.7.tgz",
],
},
"@livekit/local-inference-linux-x64-gnu": {
@@ -86,22 +86,42 @@ beforeEach(async () => {
vi.resetModules();
});
+/** Marks both listed voice packages installed, as a finished download does. */
+async function markVoiceInstalled(packagesRoot: string): Promise<void> {
+ for (const [name, body] of [
+ ["@livekit/local-inference-darwin-arm64", turn],
+ ["@livekit/local-inference-linux-x64-gnu", vad],
+ ] as const) {
+ const directory = path.join(packagesRoot, name);
+ await mkdir(directory, { recursive: true });
+ writeFileSync(
+ path.join(directory, ".simplex-model-package.json"),
+ JSON.stringify({ integrity: integrity(body) }),
+ );
+ }
+}
+
// The module reads models.json once, so every test loads it afresh.
const load = () => import("../src/model-packages.js");
describe("model packages", () => {
it("lists packages by group and resolves them only once installed", async () => {
const models = await load();
- expect(models.modelPackageNames("ocr")).toEqual(["@tesseract.js-data/eng"]);
expect(models.modelPackageNames("voice")).toEqual([
+ "@livekit/local-inference-darwin-arm64",
"@livekit/local-inference-linux-x64-gnu",
]);
- expect(models.modelPackageDirectory("tesseract.js-core", environment)).toBe(
+ expect(models.modelPackageDirectory("officeparser", environment)).toBe(
undefined,
);
expect(() =>
- models.modelPackageDirectory("@tesseract.js-data/eng", environment),
- ).toThrow("Model package @tesseract.js-data/eng is not installed");
+ models.modelPackageDirectory(
+ "@livekit/local-inference-darwin-arm64",
+ environment,
+ ),
+ ).toThrow(
+ "Model package @livekit/local-inference-darwin-arm64 is not installed",
+ );
});
it("downloads from the next registry when one serves another tarball", async () => {
@@ -109,27 +129,37 @@ describe("model packages", () => {
const fetch = vi.fn(async (url: string) =>
url.startsWith("https://registry.")
? new Response(new Uint8Array(vad))
- : new Response(new Uint8Array(eng)),
+ : new Response(new Uint8Array(turn)),
+ );
+ await models.installModelPackages(
+ ["@livekit/local-inference-darwin-arm64"],
+ environment,
+ {
+ fetch: fetch as typeof globalThis.fetch,
+ },
);
- await models.installModelPackages(["@tesseract.js-data/eng"], environment, {
- fetch: fetch as typeof globalThis.fetch,
- });
expect(fetch).toHaveBeenCalledTimes(2);
const directory = models.modelPackageDirectory(
- "@tesseract.js-data/eng",
+ "@livekit/local-inference-darwin-arm64",
environment,
)!;
expect(directory).toBe(
- path.join(home, "models", "node_modules", "@tesseract.js-data", "eng"),
+ path.join(
+ home,
+ "models",
+ "node_modules",
+ "@livekit",
+ "local-inference-darwin-arm64",
+ ),
+ );
+ expect(readFileSync(path.join(directory, "models/turn.onnx"), "utf8")).toBe(
+ "turn data",
);
expect(
- readFileSync(
- path.join(directory, "4.0.0_best_int/eng.traineddata.gz"),
- "utf8",
+ models.modelPackagesInstalled(
+ ["@livekit/local-inference-darwin-arm64"],
+ environment,
),
- ).toBe("eng data");
- expect(
- models.modelPackagesInstalled(["@tesseract.js-data/eng"], environment),
).toBe(true);
});
@@ -139,17 +169,17 @@ describe("model packages", () => {
const fetch = vi.fn(
() =>
new Promise<Response>((resolve) => {
- release = () => resolve(new Response(new Uint8Array(eng)));
+ release = () => resolve(new Response(new Uint8Array(turn)));
}),
);
const options = { fetch: fetch as unknown as typeof globalThis.fetch };
const first = models.installModelPackages(
- ["@tesseract.js-data/eng"],
+ ["@livekit/local-inference-darwin-arm64"],
environment,
options,
);
const second = models.installModelPackages(
- ["@tesseract.js-data/eng"],
+ ["@livekit/local-inference-darwin-arm64"],
environment,
options,
);
@@ -175,17 +205,22 @@ describe("model packages", () => {
).rejects.toThrow("Could not download");
expect(offline).toHaveBeenCalledOnce();
// Nothing is left behind for the next attempt to trip over.
- expect(existsSync(path.join(home, "models/node_modules/@livekit"))).toBe(
- false,
- );
+ expect(
+ existsSync(
+ path.join(
+ home,
+ "models/node_modules/@livekit/local-inference-linux-x64-gnu",
+ ),
+ ),
+ ).toBe(false);
expect(models.modelPackagesInstalled(voice, environment)).toBe(false);
});
it("keeps a package's files inside its folder", async () => {
const { unpackTarball } = await load();
- expect(unpackTarball(gunzipSync(eng)).map(([file]) => file)).toEqual([
+ expect(unpackTarball(gunzipSync(turn)).map(([file]) => file)).toEqual([
"package.json",
- "4.0.0_best_int/eng.traineddata.gz",
+ "models/turn.onnx",
]);
expect(() =>
unpackTarball(gunzipSync(tarball({ "package/../escape": "x" }))),
@@ -195,7 +230,7 @@ describe("model packages", () => {
it("installs nothing when the runtime lists no packages", async () => {
await rm(path.join(runtime.packageRoot, "models.json"));
const models = await load();
- expect(models.modelPackageNames("ocr")).toEqual([]);
+ expect(models.modelPackageNames("voice")).toEqual([]);
expect(models.modelPackagesInstalled([], environment)).toBe(true);
await models.installModelPackages([], environment, {
fetch: () => {
@@ -214,17 +249,9 @@ describe("features that need model packages", () => {
() =>
new Promise<void>((resolve) => {
installed = () => {
- const directory = path.join(
- models.modelPackagesRoot(environment),
- "@livekit/local-inference-linux-x64-gnu",
+ void markVoiceInstalled(models.modelPackagesRoot(environment)).then(
+ resolve,
);
- void mkdir(directory, { recursive: true }).then(() => {
- writeFileSync(
- path.join(directory, ".simplex-model-package.json"),
- JSON.stringify({ integrity: integrity(vad) }),
- );
- resolve();
- });
};
}),
);
@@ -292,17 +319,9 @@ describe("features that need model packages", () => {
const installModels = vi
.fn<() => Promise<void>>()
.mockRejectedValueOnce(new Error("offline"))
- .mockImplementation(async () => {
- const directory = path.join(
- models.modelPackagesRoot(environment),
- "@livekit/local-inference-linux-x64-gnu",
- );
- await mkdir(directory, { recursive: true });
- writeFileSync(
- path.join(directory, ".simplex-model-package.json"),
- JSON.stringify({ integrity: integrity(vad) }),
- );
- });
+ .mockImplementation(() =>
+ markVoiceInstalled(models.modelPackagesRoot(environment)),
+ );
const log = vi.fn();
let keys: Record<string, string> = {};
const spawnWorker = vi.fn(
@@ -339,25 +358,4 @@ describe("features that need model packages", () => {
(spawnWorker.mock.results[0]!.value as EventEmitter).emit("exit", 0, null);
await stopping;
});
-
- it("convert documents when the OCR packages cannot install", async () => {
- const { WorkerDocumentNormalizer } =
- await import("../src/document-normalizer/document-normalizer.js");
- const failure = new Error("offline");
- const onModelsUnavailable = vi.fn();
- const normalizer = new WorkerDocumentNormalizer({
- execute: async () => new TextEncoder().encode("text\n"),
- installModels: async () => {
- throw failure;
- },
- onModelsUnavailable,
- });
- const markdown = await normalizer.normalizeDocument({
- filename: "scan.pdf",
- mediaType: "application/pdf",
- source: new TextEncoder().encode("%PDF-1.4"),
- });
- expect(new TextDecoder().decode(markdown)).toBe("text\n");
- expect(onModelsUnavailable).toHaveBeenCalledWith(failure);
- });
});
diff --git a/apps/node-services/vitest.config.ts b/apps/node-services/vitest.config.ts
index 9945cd13..4272a4db 100644
--- a/apps/node-services/vitest.config.ts
+++ b/apps/node-services/vitest.config.ts
@@ -5,7 +5,7 @@ const AGENT_PROCESS_TEST = "tests/agent/executor/agent-manager-process.test.ts";
export default defineConfig({
root: import.meta.dirname,
test: {
- // Real OCR workers run alongside the existing process tests.
+ // Real conversion workers run alongside the existing process tests.
maxWorkers: 2,
testTimeout: 5_000,
environment: "node",
diff --git a/apps/teamhub/internal/document/README.md b/apps/teamhub/internal/document/README.md
index b616ec43..d03263f2 100644
--- a/apps/teamhub/internal/document/README.md
+++ b/apps/teamhub/internal/document/README.md
@@ -30,10 +30,12 @@ SHA-256 and the plain search words, with the version it came from (`native_body`
`internal/documenttext` runs the one `document_text.sync` job; `enqueue_document_text_sync` queues it from
triggers on `documents` (a new current Version, reactivation), on a new `document_bodies` row and in
`record_document_history_point`. Global search and Memory (`memory_source.personal_documents`, through
-`document_text_heads`) read it; the job skips a file Version whose text is already ready. A ready text requests no
+`document_text_heads`) read it, Memory only the texts the Wiki whitelist below admits; the job skips a file Version whose text is already ready. A ready text requests no
Wiki refresh. The Wiki reads only the bound Documents its
whitelist admits: `wiki_document_verdicts` gives each one with a text a reason to stay out or none, using the text's
-`scanned` and `longest_line_bytes` facts, and a refresh freezes the admitted ones by `document_text_version_id`.
+status and `longest_line_bytes` (a PDF without a text layer has no text and stays out as `scanned`), and a
+refresh freezes the admitted ones by `document_text_version_id`. Texts come from text layers only; there is no OCR, so
+raster images have no text.
Mail the whitelist filters out never becomes a source and is not recorded.
The Wiki's Session sources are not Documents: `wiki_session_sources` reads the Human's Room and recording Sessions
from the Memory index (`memory_index.sources` at their `source_versions` text), `wiki_current_sources` joins them
diff --git a/apps/teamhub/internal/documenttext/wiki_facts.go b/apps/teamhub/internal/documenttext/wiki_facts.go
index 94cc8a45..2f8a5853 100644
--- a/apps/teamhub/internal/documenttext/wiki_facts.go
+++ b/apps/teamhub/internal/documenttext/wiki_facts.go
@@ -1,11 +1,6 @@
package documenttext
-import (
- "bytes"
- "strings"
-
- "github.com/ledongthuc/pdf"
-)
+import "strings"
// LongestLineBytes is the UTF-8 size of the longest line of the Markdown. A
// text over one Wiki source budget enters the Wiki only when no line is over
@@ -21,28 +16,3 @@ func LongestLineBytes(markdown string) int64 {
}
return int64(longest)
}
-
-// scannedPDF reports a PDF without a text layer: no page draws any text, so
-// the normalizer read its Markdown by OCR alone and the Wiki leaves it out.
-// A file that is not a PDF, or one this reader cannot parse, counts as having
-// a text layer; the normalizer has already read it.
-func scannedPDF(source []byte) (scanned bool) {
- if !bytes.Contains(source[:min(len(source), 1024)], []byte("%PDF-")) {
- return false
- }
- defer func() {
- if recover() != nil {
- scanned = false
- }
- }()
- reader, err := pdf.NewReader(bytes.NewReader(source), int64(len(source)))
- if err != nil || reader.NumPage() < 1 {
- return false
- }
- for number := 1; number <= reader.NumPage(); number++ {
- if page := reader.Page(number); !page.V.IsNull() && len(page.Content().Text) > 0 {
- return false
- }
- }
- return true
-}
diff --git a/apps/teamhub/internal/documenttext/wiki_facts_test.go b/apps/teamhub/internal/documenttext/wiki_facts_test.go
index 6784c4ff..bf292b1f 100644
--- a/apps/teamhub/internal/documenttext/wiki_facts_test.go
+++ b/apps/teamhub/internal/documenttext/wiki_facts_test.go
@@ -1,11 +1,6 @@
package documenttext
-import (
- "bytes"
- "fmt"
- "strings"
- "testing"
-)
+import "testing"
func TestLongestLineBytesCountsUTF8BytesPerLine(t *testing.T) {
for markdown, want := range map[string]int64{
@@ -23,52 +18,3 @@ func TestLongestLineBytesCountsUTF8BytesPerLine(t *testing.T) {
}
}
}
-
-// pdfFile assembles a one-page PDF with a correct cross-reference table.
-func pdfFile(page, content string, extra ...string) []byte {
- objects := append([]string{
- "<< /Type /Catalog /Pages 2 0 R >>",
- "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
- page,
- fmt.Sprintf("<< /Length %d >>\nstream\n%s\nendstream", len(content), content),
- }, extra...)
- var file bytes.Buffer
- file.WriteString("%PDF-1.4\n")
- offsets := make([]int, len(objects))
- for index, object := range objects {
- offsets[index] = file.Len()
- fmt.Fprintf(&file, "%d 0 obj\n%s\nendobj\n", index+1, object)
- }
- start := file.Len()
- fmt.Fprintf(&file, "xref\n0 %d\n0000000000 65535 f \n", len(objects)+1)
- for _, offset := range offsets {
- fmt.Fprintf(&file, "%010d 00000 n \n", offset)
- }
- fmt.Fprintf(&file, "trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n", len(objects)+1, start)
- return file.Bytes()
-}
-
-func TestScannedPDFIsOnlyAPDFWithoutATextLayer(t *testing.T) {
- text := pdfFile("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
- "BT /F1 12 Tf 20 100 Td (Quarterly plan) Tj ET",
- "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")
- scan := pdfFile("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /XObject << /Im0 5 0 R >> >> /Contents 4 0 R >>",
- "q 200 0 0 200 0 0 cm /Im0 Do Q",
- "<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>\nstream\n\xff\nendstream")
- for name, test := range map[string]struct {
- source []byte
- want bool
- }{
- "text layer": {text, false},
- "scan": {scan, true},
- "markdown": {[]byte("# Notes\n\nPlain text."), false},
- "broken PDF": {[]byte("%PDF-1.4\nnot really a PDF"), false},
- "truncated scan": {scan[:len(scan)/2], false},
- "empty": {nil, false},
- "PDF magic later": {append([]byte(strings.Repeat(" ", 2000)), scan...), false},
- } {
- if got := scannedPDF(test.source); got != test.want {
- t.Errorf("%s: scannedPDF=%v, want %v", name, got, test.want)
- }
- }
-}
diff --git a/apps/teamhub/internal/documenttext/worker.go b/apps/teamhub/internal/documenttext/worker.go
index b090a3d5..804c76ff 100644
--- a/apps/teamhub/internal/documenttext/worker.go
+++ b/apps/teamhub/internal/documenttext/worker.go
@@ -133,8 +133,6 @@ func AddJobWorkers(workers *river.Workers, worker *Worker) {
type extracted struct {
Status string
Markdown string
- // Scanned marks a PDF whose Markdown came from OCR alone.
- Scanned bool
}
// sync extracts the Document's current version and records the result. The
@@ -172,7 +170,6 @@ func (w *Worker) sync(ctx context.Context, args SyncArgs, finalAttempt bool) err
params.Markdown = result.Markdown
params.MarkdownSha256 = pgtype.Text{String: hex.EncodeToString(digest[:]), Valid: true}
params.SearchText = document.MarkdownToSearchText(result.Markdown)
- params.Scanned = result.Scanned
params.LongestLineBytes = LongestLineBytes(result.Markdown)
}
if _, err := w.queries.UpsertDocumentText(ctx, params); err != nil {
@@ -227,7 +224,7 @@ func (w *Worker) extract(ctx context.Context, documentID string, source store.Ge
if normalized.Status != StatusReady {
return extracted{Status: normalized.Status}, nil
}
- return extracted{Status: StatusReady, Markdown: string(normalized.Markdown), Scanned: scannedPDF(source)}, nil
+ return extracted{Status: StatusReady, Markdown: string(normalized.Markdown)}, nil
default:
return extracted{}, fmt.Errorf("unknown Document text source kind %q", source.SourceKind)
}
diff --git a/apps/teamhub/internal/documenttext/worker_test.go b/apps/teamhub/internal/documenttext/worker_test.go
index 519c3a81..0070b91f 100644
--- a/apps/teamhub/internal/documenttext/worker_test.go
+++ b/apps/teamhub/internal/documenttext/worker_test.go
@@ -138,11 +138,11 @@ func TestWorkerSyncsNativeAndFileDocuments(t *testing.T) {
if got := byDocument["doc_native"]; got.Status != StatusReady || got.SourceID != "7" || got.SourceKind != "native_body" ||
got.SearchText != "Release checklist Freeze at 4pm" || got.Markdown != "# Release checklist\n\n- **Freeze** at 4pm" ||
got.MarkdownSha256.String != "a6ce43e2dd71ed3f67404923787edc472c04bdd102f2bdcc0aabb764ae8c8ba6" ||
- got.LongestLineBytes != 19 || got.Scanned {
+ got.LongestLineBytes != 19 {
t.Fatalf("native upsert = %+v", got)
}
if got := byDocument["doc_file"]; got.Status != StatusReady || got.SourceID != "ver_1" ||
- got.SearchText != "Invoice total: 1,200 USD item qty widget 3" || !got.MarkdownSha256.Valid || got.Scanned {
+ got.SearchText != "Invoice total: 1,200 USD item qty widget 3" || !got.MarkdownSha256.Valid {
t.Fatalf("file upsert = %+v", got)
}
if got := byDocument["doc_scan"]; got.Status != StatusNoText || got.SearchText != "" || got.Markdown != "" || got.MarkdownSha256.Valid {
@@ -219,28 +219,3 @@ func TestWorkerSkipsDocumentWithoutCurrentSource(t *testing.T) {
t.Fatalf("upserts=%+v", queries.upserts)
}
}
-
-// A PDF whose pages draw no text was read by OCR alone; its text says so.
-func TestWorkerMarksPDFTextsReadByOCRAlone(t *testing.T) {
- t.Parallel()
- scan := pdfFile("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /XObject << /Im0 5 0 R >> >> /Contents 4 0 R >>",
- "q 200 0 0 200 0 0 cm /Im0 Do Q",
- "<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>\nstream\n\xff\nendstream")
- queries := &fakeQueries{rows: 1, sources: map[string]store.GetCurrentDocumentTextSourceRow{
- "doc_scan": {TenantID: "tenant_a", SourceKind: "file_version", SourceID: "ver_scan"},
- }}
- documents := fakeDocuments{versions: map[string]document.VersionContent{
- "ver_scan": {Version: document.Version{ID: "ver_scan", Filename: "receipt.pdf", MediaType: "application/pdf", SizeBytes: int64(len(scan))}, ObjectKey: "obj_scan"},
- }}
- normalizer := newTestNormalizer(t, func(writer http.ResponseWriter, _ *http.Request) {
- _, _ = writer.Write([]byte("RECEIPT total 12"))
- })
- worker := NewWorker(queries, documents, fakeObjects{"obj_scan": string(scan)}, normalizer, nil)
- if err := worker.Work(context.Background(), syncJob("doc_scan", 1)); err != nil {
- t.Fatal(err)
- }
- if len(queries.upserts) != 1 || queries.upserts[0].Status != StatusReady || !queries.upserts[0].Scanned ||
- queries.upserts[0].LongestLineBytes != 16 {
- t.Fatalf("upserts=%+v", queries.upserts)
- }
-}
diff --git a/apps/teamhub/internal/personalprofile/admission.go b/apps/teamhub/internal/personalprofile/admission.go
index b698748d..948241b0 100644
--- a/apps/teamhub/internal/personalprofile/admission.go
+++ b/apps/teamhub/internal/personalprofile/admission.go
@@ -19,7 +19,7 @@ func (s *Service) fileAdmission(ctx context.Context, tenant, version string) (ad
err = s.pool.QueryRow(ctx, `SELECT
t.source_id IS NOT NULL AND coalesce(d.native_import_status,'completed') IN ('completed','failed')
AND source_rejection_reason(d.native_import_status, v.filename, v.representation_format,
- t.source_kind, v.media_type, t.status, t.scanned, octet_length(t.markdown), t.longest_line_bytes) IS NULL,
+ t.source_kind, v.media_type, t.status, octet_length(t.markdown), t.longest_line_bytes) IS NULL,
(t.source_id IS NULL OR coalesce(d.native_import_status,'completed') NOT IN ('completed','failed')) AND coalesce(d.native_import_status,'completed') <> 'failed'
FROM document_versions v JOIN documents d ON d.id=v.document_id AND d.tenant_id=v.tenant_id
LEFT JOIN document_texts t ON t.document_id=d.id AND t.source_kind='file_version' AND t.source_id=v.id
@@ -98,7 +98,7 @@ func (s *Service) transientAdmission(ctx context.Context, documents []composio.A
sizes[i] = int64(len(d.Markdown))
lines[i] = documenttext.LongestLineBytes(string(d.Markdown))
}
- rows, err := s.pool.Query(ctx, `SELECT source_rejection_reason(NULL, name,'markdown','file_version','text/markdown','ready',false,size,longest) IS NULL
+ rows, err := s.pool.Query(ctx, `SELECT source_rejection_reason(NULL, name,'markdown','file_version','text/markdown','ready',size,longest) IS NULL
FROM unnest($1::text[],$2::bigint[],$3::bigint[]) WITH ORDINALITY AS inputs(name,size,longest,n) ORDER BY n`, names, sizes, lines)
if err != nil {
return nil, err
diff --git a/apps/teamhub/internal/store/document_text.sql.go b/apps/teamhub/internal/store/document_text.sql.go
index 0208e8bf..343fa724 100644
--- a/apps/teamhub/internal/store/document_text.sql.go
+++ b/apps/teamhub/internal/store/document_text.sql.go
@@ -50,21 +50,21 @@ WITH current AS (
(CASE WHEN document.format='blocknote' THEN body.seq::text ELSE document.current_version_id END)::text AS source_id
FROM documents document
LEFT JOIN document_bodies body ON body.document_id=document.id
- WHERE document.id=$9::text AND document.status='active'
+ WHERE document.id=$8::text AND document.status='active'
)
INSERT INTO document_texts (document_id, tenant_id, source_kind, source_id, status,
- markdown, markdown_sha256, search_text, scanned,
+ markdown, markdown_sha256, search_text,
longest_line_bytes, updated_at)
SELECT current.document_id, current.tenant_id, current.source_kind, current.source_id,
$1::text, $2::text, $3::text,
- $4::text, $5::boolean,
- $6::bigint, clock_timestamp()
+ $4::text,
+ $5::bigint, clock_timestamp()
FROM current
-WHERE current.source_kind=$7::text AND current.source_id=$8::text
+WHERE current.source_kind=$6::text AND current.source_id=$7::text
ON CONFLICT (document_id) DO UPDATE
SET source_kind=EXCLUDED.source_kind, source_id=EXCLUDED.source_id, status=EXCLUDED.status,
markdown=EXCLUDED.markdown, markdown_sha256=EXCLUDED.markdown_sha256,
- search_text=EXCLUDED.search_text, scanned=EXCLUDED.scanned,
+ search_text=EXCLUDED.search_text,
longest_line_bytes=EXCLUDED.longest_line_bytes, updated_at=EXCLUDED.updated_at
`
@@ -73,7 +73,6 @@ type UpsertDocumentTextParams struct {
Markdown string `json:"markdown"`
MarkdownSha256 pgtype.Text `json:"markdown_sha256"`
SearchText string `json:"search_text"`
- Scanned bool `json:"scanned"`
LongestLineBytes int64 `json:"longest_line_bytes"`
SourceKind string `json:"source_kind"`
SourceID string `json:"source_id"`
@@ -89,7 +88,6 @@ func (q *Queries) UpsertDocumentText(ctx context.Context, arg UpsertDocumentText
arg.Markdown,
arg.MarkdownSha256,
arg.SearchText,
- arg.Scanned,
arg.LongestLineBytes,
arg.SourceKind,
arg.SourceID,
diff --git a/apps/teamhub/internal/store/models.go b/apps/teamhub/internal/store/models.go
index b1913268..77c9a25e 100644
--- a/apps/teamhub/internal/store/models.go
+++ b/apps/teamhub/internal/store/models.go
@@ -660,7 +660,6 @@ type DocumentText struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
Markdown string `json:"markdown"`
MarkdownSha256 pgtype.Text `json:"markdown_sha256"`
- Scanned bool `json:"scanned"`
LongestLineBytes int64 `json:"longest_line_bytes"`
}
diff --git a/apps/teamhub/internal/store/queries/document_text.sql b/apps/teamhub/internal/store/queries/document_text.sql
index 7def3a63..10053050 100644
--- a/apps/teamhub/internal/store/queries/document_text.sql
+++ b/apps/teamhub/internal/store/queries/document_text.sql
@@ -29,16 +29,16 @@ WITH current AS (
WHERE document.id=sqlc.arg(document_id)::text AND document.status='active'
)
INSERT INTO document_texts (document_id, tenant_id, source_kind, source_id, status,
- markdown, markdown_sha256, search_text, scanned,
+ markdown, markdown_sha256, search_text,
longest_line_bytes, updated_at)
SELECT current.document_id, current.tenant_id, current.source_kind, current.source_id,
sqlc.arg(status)::text, sqlc.arg(markdown)::text, sqlc.narg(markdown_sha256)::text,
- sqlc.arg(search_text)::text, sqlc.arg(scanned)::boolean,
+ sqlc.arg(search_text)::text,
sqlc.arg(longest_line_bytes)::bigint, clock_timestamp()
FROM current
WHERE current.source_kind=sqlc.arg(source_kind)::text AND current.source_id=sqlc.arg(source_id)::text
ON CONFLICT (document_id) DO UPDATE
SET source_kind=EXCLUDED.source_kind, source_id=EXCLUDED.source_id, status=EXCLUDED.status,
markdown=EXCLUDED.markdown, markdown_sha256=EXCLUDED.markdown_sha256,
- search_text=EXCLUDED.search_text, scanned=EXCLUDED.scanned,
+ search_text=EXCLUDED.search_text,
longest_line_bytes=EXCLUDED.longest_line_bytes, updated_at=EXCLUDED.updated_at;
diff --git a/apps/teamhub/migrations/00871_drop_scanned_document_texts.sql b/apps/teamhub/migrations/00871_drop_scanned_document_texts.sql
new file mode 100644
index 00000000..69aa2f59
--- /dev/null
+++ b/apps/teamhub/migrations/00871_drop_scanned_document_texts.sql
@@ -0,0 +1,148 @@
+-- +goose Up
+-- Document texts come only from text layers, never from OCR, so a ready PDF
+-- text always has one and the scanned flag goes away; a PDF without text is
+-- still rejected from the Wiki as scanned. Texts already stored are kept as
+-- they are.
+DROP VIEW public.wiki_current_sources;
+DROP VIEW public.wiki_document_verdicts;
+DROP FUNCTION public.source_rejection_reason(text, text, text, text, text, text, boolean, bigint, bigint);
+ALTER TABLE document_texts DROP COLUMN scanned;
+
+-- +goose StatementBegin
+CREATE FUNCTION public.source_rejection_reason(import_status text, file_name text, representation text, kind text, mime text, text_status text, text_bytes bigint, line_bytes bigint) RETURNS text
+ LANGUAGE sql IMMUTABLE
+ AS $$
+SELECT
+ CASE
+ WHEN import_status = 'failed' THEN 'unreadable'
+ WHEN lower(coalesce(file_name, '')) LIKE '%.crdownload'
+ OR lower(coalesce(representation, '')) = 'crdownload' THEN 'unsupported_type'
+ WHEN kind = 'file_version'
+ AND NOT wiki_reads_file_format(mime, file_name, representation)
+ THEN 'unsupported_type'
+ WHEN text_status = 'unsupported' THEN 'unsupported_type'
+ WHEN text_status = 'too_large' THEN 'too_large'
+ WHEN text_status = 'failed' THEN 'unreadable'
+ WHEN text_status = 'no_text' AND kind = 'file_version'
+ AND (lower(trim(split_part(mime, ';', 1))) = 'application/pdf'
+ OR lower(file_name) LIKE '%.pdf'
+ OR lower(representation) = 'pdf') THEN 'scanned'
+ WHEN text_status = 'no_text' OR text_bytes = 0 THEN 'no_text'
+ WHEN line_bytes > 144000 THEN 'too_large'
+ END
+$$;
+-- +goose StatementEnd
+
+CREATE VIEW public.wiki_document_verdicts AS
+ SELECT binding.wiki_id,
+ binding.tenant_id,
+ document.id AS document_id,
+ COALESCE(version.filename, document.title) AS filename,
+ CASE
+ WHEN (item.document_id IS NULL) THEN 'my_pages'::text
+ ELSE COALESCE(connection.provider, 'mail'::text)
+ END AS source,
+ public.document_text_version_id(document.id, text.source_kind, text.source_id) AS version_id,
+ (octet_length(text.markdown))::bigint AS size_bytes,
+ text.updated_at AS decided_at,
+ public.source_rejection_reason(document.native_import_status, version.filename, version.representation_format, text.source_kind, version.media_type, text.status, (octet_length(text.markdown))::bigint, text.longest_line_bytes) AS reason
+ FROM (((((public.document_context_bindings binding
+ JOIN public.documents document ON (((document.id = binding.document_id) AND (document.tenant_id = binding.tenant_id) AND (document.status = 'active'::text))))
+ JOIN public.document_texts text ON ((text.document_id = document.id)))
+ LEFT JOIN public.document_versions version ON (((text.source_kind = 'file_version'::text) AND (version.id = text.source_id) AND (version.document_id = document.id))))
+ LEFT JOIN public.wiki_source_items item ON (((item.tenant_id = document.tenant_id) AND (item.document_id = document.id))))
+ LEFT JOIN public.external_connections connection ON ((connection.id = split_part(item.source_key, ':'::text, 2))))
+ WHERE ((binding.binding_kind = 'wiki_source'::text) AND (binding.status = 'active'::text) AND (COALESCE(document.native_import_status, 'completed'::text) = ANY (ARRAY['completed'::text, 'failed'::text])) AND (NOT (EXISTS ( SELECT 1
+ FROM public.document_context_bindings page
+ WHERE ((page.document_id = document.id) AND (page.tenant_id = document.tenant_id) AND (page.binding_kind = 'wiki_page'::text))))));
+
+CREATE VIEW public.wiki_current_sources AS
+ SELECT verdict.wiki_id,
+ verdict.tenant_id,
+ 'document'::text AS source_kind,
+ verdict.document_id AS source_id,
+ verdict.version_id,
+ verdict.size_bytes
+ FROM public.wiki_document_verdicts verdict
+ WHERE (verdict.reason IS NULL)
+UNION ALL
+ SELECT wiki_session_sources.wiki_id,
+ wiki_session_sources.tenant_id,
+ 'session'::text AS source_kind,
+ wiki_session_sources.source_id,
+ wiki_session_sources.version_id,
+ wiki_session_sources.size_bytes
+ FROM public.wiki_session_sources;
+
+-- +goose Down
+DROP VIEW public.wiki_current_sources;
+DROP VIEW public.wiki_document_verdicts;
+DROP FUNCTION public.source_rejection_reason(text, text, text, text, text, text, bigint, bigint);
+ALTER TABLE document_texts ADD COLUMN scanned boolean DEFAULT false NOT NULL;
+
+-- +goose StatementBegin
+CREATE FUNCTION public.source_rejection_reason(import_status text, file_name text, representation text, kind text, mime text, text_status text, is_scanned boolean, text_bytes bigint, line_bytes bigint) RETURNS text
+ LANGUAGE sql IMMUTABLE
+ AS $$
+SELECT
+ CASE
+ WHEN import_status = 'failed' THEN 'unreadable'
+ WHEN lower(coalesce(file_name, '')) LIKE '%.crdownload'
+ OR lower(coalesce(representation, '')) = 'crdownload' THEN 'unsupported_type'
+ WHEN kind = 'file_version'
+ AND NOT wiki_reads_file_format(mime, file_name, representation)
+ THEN 'unsupported_type'
+ WHEN text_status = 'unsupported' THEN 'unsupported_type'
+ WHEN text_status = 'too_large' THEN 'too_large'
+ WHEN text_status = 'failed' THEN 'unreadable'
+ WHEN is_scanned THEN 'scanned'
+ WHEN text_status = 'no_text' AND kind = 'file_version'
+ AND (lower(trim(split_part(mime, ';', 1))) = 'application/pdf'
+ OR lower(file_name) LIKE '%.pdf'
+ OR lower(representation) = 'pdf') THEN 'scanned'
+ WHEN text_status = 'no_text' OR text_bytes = 0 THEN 'no_text'
+ WHEN line_bytes > 144000 THEN 'too_large'
+ END
+$$;
+-- +goose StatementEnd
+
+CREATE VIEW public.wiki_document_verdicts AS
+ SELECT binding.wiki_id,
+ binding.tenant_id,
+ document.id AS document_id,
+ COALESCE(version.filename, document.title) AS filename,
+ CASE
+ WHEN (item.document_id IS NULL) THEN 'my_pages'::text
+ ELSE COALESCE(connection.provider, 'mail'::text)
+ END AS source,
+ public.document_text_version_id(document.id, text.source_kind, text.source_id) AS version_id,
+ (octet_length(text.markdown))::bigint AS size_bytes,
+ text.updated_at AS decided_at,
+ public.source_rejection_reason(document.native_import_status, version.filename, version.representation_format, text.source_kind, version.media_type, text.status, text.scanned, (octet_length(text.markdown))::bigint, text.longest_line_bytes) AS reason
+ FROM (((((public.document_context_bindings binding
+ JOIN public.documents document ON (((document.id = binding.document_id) AND (document.tenant_id = binding.tenant_id) AND (document.status = 'active'::text))))
+ JOIN public.document_texts text ON ((text.document_id = document.id)))
+ LEFT JOIN public.document_versions version ON (((text.source_kind = 'file_version'::text) AND (version.id = text.source_id) AND (version.document_id = document.id))))
+ LEFT JOIN public.wiki_source_items item ON (((item.tenant_id = document.tenant_id) AND (item.document_id = document.id))))
+ LEFT JOIN public.external_connections connection ON ((connection.id = split_part(item.source_key, ':'::text, 2))))
+ WHERE ((binding.binding_kind = 'wiki_source'::text) AND (binding.status = 'active'::text) AND (COALESCE(document.native_import_status, 'completed'::text) = ANY (ARRAY['completed'::text, 'failed'::text])) AND (NOT (EXISTS ( SELECT 1
+ FROM public.document_context_bindings page
+ WHERE ((page.document_id = document.id) AND (page.tenant_id = document.tenant_id) AND (page.binding_kind = 'wiki_page'::text))))));
+
+CREATE VIEW public.wiki_current_sources AS
+ SELECT verdict.wiki_id,
+ verdict.tenant_id,
+ 'document'::text AS source_kind,
+ verdict.document_id AS source_id,
+ verdict.version_id,
+ verdict.size_bytes
+ FROM public.wiki_document_verdicts verdict
+ WHERE (verdict.reason IS NULL)
+UNION ALL
+ SELECT wiki_session_sources.wiki_id,
+ wiki_session_sources.tenant_id,
+ 'session'::text AS source_kind,
+ wiki_session_sources.source_id,
+ wiki_session_sources.version_id,
+ wiki_session_sources.size_bytes
+ FROM public.wiki_session_sources;
diff --git a/apps/teamhub/migrations/00872_memory_raw_follows_wiki_whitelist.sql b/apps/teamhub/migrations/00872_memory_raw_follows_wiki_whitelist.sql
new file mode 100644
index 00000000..c73f72f4
--- /dev/null
+++ b/apps/teamhub/migrations/00872_memory_raw_follows_wiki_whitelist.sql
@@ -0,0 +1,181 @@
+-- +goose Up
+-- My pages and imported mail enter the Memory index only when the Wiki
+-- whitelist would admit them. Sources already indexed that no longer qualify
+-- leave the index on Memory's next hourly reconciliation, which deletes every
+-- My pages or mail source missing from this inventory with its chunks and
+-- facts.
+-- +goose StatementBegin
+CREATE OR REPLACE FUNCTION memory_source.personal_documents(p_tenant_id text, p_owner_actor_id text) RETURNS TABLE(folder_path text, origin_kind text, document_id text, text_source_kind text, text_source_id text, title text, filename text, media_type text, markdown_sha256 text, created_at timestamp with time zone)
+ LANGUAGE sql STABLE
+ AS $$
+WITH RECURSIVE tree AS (
+ SELECT placement.id, placement.parent_id, placement.node_kind,
+ placement.name, placement.document_id,
+ CASE WHEN placement.node_kind = 'folder' THEN placement.name ELSE '' END AS folder_path
+ FROM document_placements placement
+ WHERE placement.tenant_id = p_tenant_id
+ AND placement.owner_human_actor_id = p_owner_actor_id
+ AND placement.scope_kind = 'personal'
+ AND placement.parent_id IS NULL
+ AND placement.deleted_at IS NULL
+ UNION ALL
+ SELECT child.id, child.parent_id, child.node_kind, child.name,
+ child.document_id,
+ CASE WHEN child.node_kind = 'folder'
+ THEN concat_ws('/', nullif(tree.folder_path, ''), child.name)
+ ELSE tree.folder_path END
+ FROM document_placements child
+ JOIN tree ON tree.id = child.parent_id
+ WHERE child.tenant_id = p_tenant_id
+ AND child.owner_human_actor_id = p_owner_actor_id
+ AND child.scope_kind = 'personal'
+ AND child.deleted_at IS NULL
+), candidates AS (
+ SELECT tree.document_id, tree.folder_path, 'my_pages'::text AS origin_kind
+ FROM tree
+ WHERE tree.node_kind = 'document'
+ UNION ALL
+ SELECT item.document_id, '', 'mail'
+ FROM wiki_source_items item
+ JOIN document_context_bindings binding
+ ON binding.document_id = item.document_id
+ AND binding.tenant_id = item.tenant_id
+ AND binding.binding_kind = 'wiki_source'
+ AND binding.status = 'active'
+ JOIN personal_wikis wiki
+ ON wiki.id = binding.wiki_id
+ AND wiki.tenant_id = item.tenant_id
+ AND wiki.owner_actor_id = item.owner_actor_id
+ AND wiki.deleted_at IS NULL
+ WHERE item.tenant_id = p_tenant_id
+ AND item.owner_actor_id = p_owner_actor_id
+), current_documents AS (
+ SELECT DISTINCT ON (candidates.document_id)
+ candidates.document_id, candidates.folder_path, candidates.origin_kind
+ FROM candidates
+ ORDER BY candidates.document_id, candidates.origin_kind, candidates.folder_path
+)
+SELECT current_documents.folder_path,
+ current_documents.origin_kind,
+ document.id,
+ text.source_kind,
+ text.source_id,
+ document.title,
+ coalesce(version.filename, document.title),
+ coalesce(version.media_type, 'text/markdown'),
+ text.markdown_sha256,
+ coalesce(version.created_at, text.updated_at)
+FROM current_documents
+JOIN documents document
+ ON document.id = current_documents.document_id
+ AND document.tenant_id = p_tenant_id
+ AND document.status = 'active'
+JOIN document_texts text
+ ON text.document_id = document.id
+ AND text.status = 'ready'
+LEFT JOIN document_versions version
+ ON text.source_kind = 'file_version'
+ AND version.id = text.source_id
+ AND version.document_id = document.id
+WHERE NOT EXISTS (
+ SELECT 1 FROM document_context_bindings page
+ WHERE page.document_id = document.id AND page.tenant_id = document.tenant_id
+ AND page.binding_kind = 'wiki_page')
+ AND (text.source_kind = 'native_body'
+ OR EXISTS (SELECT 1 FROM document_text_heads head
+ WHERE head.id = document.id AND head.tenant_id = document.tenant_id))
+ -- Memory keeps only what the Wiki can record: the same rejection rule
+ -- the Wiki whitelist applies keeps scans, images, spreadsheets, data and
+ -- code files out of Raw.
+ AND public.source_rejection_reason(document.native_import_status,
+ version.filename, version.representation_format, text.source_kind,
+ version.media_type, text.status,
+ octet_length(text.markdown)::bigint, text.longest_line_bytes) IS NULL
+ORDER BY current_documents.folder_path, document.id
+$$;
+-- +goose StatementEnd
+
+-- +goose Down
+-- +goose StatementBegin
+CREATE OR REPLACE FUNCTION memory_source.personal_documents(p_tenant_id text, p_owner_actor_id text) RETURNS TABLE(folder_path text, origin_kind text, document_id text, text_source_kind text, text_source_id text, title text, filename text, media_type text, markdown_sha256 text, created_at timestamp with time zone)
+ LANGUAGE sql STABLE
+ AS $$
+WITH RECURSIVE tree AS (
+ SELECT placement.id, placement.parent_id, placement.node_kind,
+ placement.name, placement.document_id,
+ CASE WHEN placement.node_kind = 'folder' THEN placement.name ELSE '' END AS folder_path
+ FROM document_placements placement
+ WHERE placement.tenant_id = p_tenant_id
+ AND placement.owner_human_actor_id = p_owner_actor_id
+ AND placement.scope_kind = 'personal'
+ AND placement.parent_id IS NULL
+ AND placement.deleted_at IS NULL
+ UNION ALL
+ SELECT child.id, child.parent_id, child.node_kind, child.name,
+ child.document_id,
+ CASE WHEN child.node_kind = 'folder'
+ THEN concat_ws('/', nullif(tree.folder_path, ''), child.name)
+ ELSE tree.folder_path END
+ FROM document_placements child
+ JOIN tree ON tree.id = child.parent_id
+ WHERE child.tenant_id = p_tenant_id
+ AND child.owner_human_actor_id = p_owner_actor_id
+ AND child.scope_kind = 'personal'
+ AND child.deleted_at IS NULL
+), candidates AS (
+ SELECT tree.document_id, tree.folder_path, 'my_pages'::text AS origin_kind
+ FROM tree
+ WHERE tree.node_kind = 'document'
+ UNION ALL
+ SELECT item.document_id, '', 'mail'
+ FROM wiki_source_items item
+ JOIN document_context_bindings binding
+ ON binding.document_id = item.document_id
+ AND binding.tenant_id = item.tenant_id
+ AND binding.binding_kind = 'wiki_source'
+ AND binding.status = 'active'
+ JOIN personal_wikis wiki
+ ON wiki.id = binding.wiki_id
+ AND wiki.tenant_id = item.tenant_id
+ AND wiki.owner_actor_id = item.owner_actor_id
+ AND wiki.deleted_at IS NULL
+ WHERE item.tenant_id = p_tenant_id
+ AND item.owner_actor_id = p_owner_actor_id
+), current_documents AS (
+ SELECT DISTINCT ON (candidates.document_id)
+ candidates.document_id, candidates.folder_path, candidates.origin_kind
+ FROM candidates
+ ORDER BY candidates.document_id, candidates.origin_kind, candidates.folder_path
+)
+SELECT current_documents.folder_path,
+ current_documents.origin_kind,
+ document.id,
+ text.source_kind,
+ text.source_id,
+ document.title,
+ coalesce(version.filename, document.title),
+ coalesce(version.media_type, 'text/markdown'),
+ text.markdown_sha256,
+ coalesce(version.created_at, text.updated_at)
+FROM current_documents
+JOIN documents document
+ ON document.id = current_documents.document_id
+ AND document.tenant_id = p_tenant_id
+ AND document.status = 'active'
+JOIN document_texts text
+ ON text.document_id = document.id
+ AND text.status = 'ready'
+LEFT JOIN document_versions version
+ ON text.source_kind = 'file_version'
+ AND version.id = text.source_id
+ AND version.document_id = document.id
+WHERE NOT EXISTS (
+ SELECT 1 FROM document_context_bindings page
+ WHERE page.document_id = document.id AND page.tenant_id = document.tenant_id
+ AND page.binding_kind = 'wiki_page')
+ AND (text.source_kind = 'native_body'
+ OR EXISTS (SELECT 1 FROM document_text_heads head
+ WHERE head.id = document.id AND head.tenant_id = document.tenant_id))
+ORDER BY current_documents.folder_path, document.id
+$$;
+-- +goose StatementEnd
diff --git a/apps/teamhub/tests/integration/document_text_fixture_test.go b/apps/teamhub/tests/integration/document_text_fixture_test.go
index 9c775ae2..2ea2ba16 100644
--- a/apps/teamhub/tests/integration/document_text_fixture_test.go
+++ b/apps/teamhub/tests/integration/document_text_fixture_test.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"io"
+ "regexp"
"testing"
"github.com/jackc/pgx/v5"
@@ -117,6 +118,21 @@ func (o fixtureTextObjects) Open(ctx context.Context, key string) (io.ReadCloser
type fixtureTextNormalizer struct{}
+// Normalize returns the bytes as Markdown, except that a real PDF gives only
+// the strings its pages draw, as the real normalizer reads only the text layer.
func (fixtureTextNormalizer) Normalize(_ context.Context, source documenttext.NormalizationSource) (documenttext.NormalizedDocument, error) {
- return documenttext.NormalizedDocument{Status: documenttext.StatusReady, Markdown: source.Bytes}, nil
+ markdown := source.Bytes
+ if bytes.HasPrefix(source.Bytes, []byte("%PDF-")) {
+ var drawn [][]byte
+ for _, match := range fixturePDFText.FindAllSubmatch(source.Bytes, -1) {
+ drawn = append(drawn, match[1])
+ }
+ markdown = bytes.Join(drawn, []byte("\n"))
+ }
+ if len(markdown) == 0 {
+ return documenttext.NormalizedDocument{Status: documenttext.StatusNoText}, nil
+ }
+ return documenttext.NormalizedDocument{Status: documenttext.StatusReady, Markdown: markdown}, nil
}
+
+var fixturePDFText = regexp.MustCompile(`\(([^)]*)\) Tj`)
diff --git a/apps/teamhub/tests/integration/memory_source_views_test.go b/apps/teamhub/tests/integration/memory_source_views_test.go
index 452a52a3..80c4994f 100644
--- a/apps/teamhub/tests/integration/memory_source_views_test.go
+++ b/apps/teamhub/tests/integration/memory_source_views_test.go
@@ -143,6 +143,33 @@ func TestMemorySourceViewsCarryMemoryAuthorization(t *testing.T) {
assertMemorySourceRows(t, pool, `
SELECT memory_source.human_can_read_document('actor_me_a','tenant_document_a','document_memory_page')`,
[][]any{{false}})
+ // Files the Wiki cannot record stay out of Raw too: a spreadsheet with a
+ // ready text and a scanned PDF without one are not listed.
+ if _, err = pool.Exec(ctx, `
+ INSERT INTO documents(
+ id,tenant_id,title,format,owner_actor_id,owner_actor_kind,creator_actor_id,creator_actor_kind,status
+ ) VALUES
+ ('document_memory_sheet','tenant_document_a','Sheet','markdown','actor_human_a','human','actor_human_a','human','active'),
+ ('document_memory_scan','tenant_document_a','Scan','markdown','actor_human_a','human','actor_human_a','human','active');
+ INSERT INTO document_versions(
+ id,tenant_id,document_id,version_number,filename,representation_format,media_type,
+ size_bytes,sha256,content_object_id,source,created_by_actor_id
+ ) VALUES
+ ('version_document_memory_sheet','tenant_document_a','document_memory_sheet',1,'sheet.csv','csv','text/csv',
+ 1,repeat('e',64),'object_document_memory_sheet','ordinary_upload','actor_human_a'),
+ ('version_document_memory_scan','tenant_document_a','document_memory_scan',1,'scan.pdf','pdf','application/pdf',
+ 1,repeat('f',64),'object_document_memory_scan','ordinary_upload','actor_human_a');
+ UPDATE documents SET current_version_id='version_' || id
+ WHERE id IN ('document_memory_sheet','document_memory_scan');
+ INSERT INTO document_texts(document_id,tenant_id,source_kind,source_id,status,markdown,markdown_sha256,search_text)
+ VALUES('document_memory_sheet','tenant_document_a','file_version','version_document_memory_sheet','ready','| a |',repeat('e',64),'a'),
+ ('document_memory_scan','tenant_document_a','file_version','version_document_memory_scan','no_text','',NULL,'');
+ INSERT INTO document_placements(id,tenant_id,scope_kind,owner_human_actor_id,parent_id,node_kind,name,document_id,sort_key) VALUES
+ ('placement_memory_sheet','tenant_document_a','personal','actor_human_a','placement_memory_folder','document',NULL,'document_memory_sheet','d'),
+ ('placement_memory_scan','tenant_document_a','personal','actor_human_a','placement_memory_folder','document',NULL,'document_memory_scan','e');
+ `); err != nil {
+ t.Fatal(err)
+ }
// Every page is read through its normalized text: a native page by its
// body sequence, a file by its Version.
assertMemorySourceRows(t, pool, `
diff --git a/apps/teamhub/tests/integration/wiki_source_whitelist_test.go b/apps/teamhub/tests/integration/wiki_source_whitelist_test.go
index ecbaa2a4..f3e74d4c 100644
--- a/apps/teamhub/tests/integration/wiki_source_whitelist_test.go
+++ b/apps/teamhub/tests/integration/wiki_source_whitelist_test.go
@@ -153,17 +153,15 @@ func TestWikiSourceWhitelistAdmitsAndSkipsWithReasons(t *testing.T) {
if listed != len(skipped) {
t.Fatalf("whitelist kept out %d sources, want %d", listed, len(skipped))
}
- // Search and Memory still read every text the Wiki leaves out; the empty
- // file has none.
- var withText []string
- for id, reason := range skipped {
- if reason != "no_text" {
- withText = append(withText, id)
- }
+ // Memory indexes only what the Wiki can record, so every source the
+ // whitelist keeps out is missing from its inventory as well.
+ var ids []string
+ for id := range skipped {
+ ids = append(ids, id)
}
- var searchable int
+ var indexed int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM memory_source.personal_documents('tenant_document_a','actor_human_a')
- WHERE document_id = ANY($1)`, withText).Scan(&searchable); err != nil || searchable != len(withText) {
- t.Fatalf("searchable skipped sources=%d want %d err=%v", searchable, len(withText), err)
+ WHERE document_id = ANY($1)`, ids).Scan(&indexed); err != nil || indexed != 0 {
+ t.Fatalf("Memory lists %d whitelist-skipped sources, want 0 err=%v", indexed, err)
}
}
diff --git a/contracts/generated/typescript/src/generated/node-services-internal/types.ts b/contracts/generated/typescript/src/generated/node-services-internal/types.ts
index 42e6c9d7..d0748416 100644
--- a/contracts/generated/typescript/src/generated/node-services-internal/types.ts
+++ b/contracts/generated/typescript/src/generated/node-services-internal/types.ts
@@ -441,13 +441,13 @@ export interface paths {
* disconnects leaves the line and stops its conversion. Supported
* sources include UTF-8 Markdown, plain text, HTML, CSV/TSV, JSON, XML,
* YAML and other text, plus PDF, DOC, DOCX, XLSX, PPTX, ZIP/gzip
- * archives of those types, SVG, and raster images. ZIP and gzip unwrap
- * at most one archive layer; nested ZIP or gzip is unsupported. ZIP
- * members of supported non-archive types are extracted within
- * archive-safety limits. PDF pages keep their text layer, and pages
- * with raster images are also recognized with English and Simplified
- * Chinese OCR; raster images are recognized the same way. Audio, video,
- * RAR/7z/tar, and legacy Excel/PowerPoint binaries remain unsupported.
+ * archives of those types, and SVG. ZIP and gzip unwrap at most one
+ * archive layer; nested ZIP or gzip is unsupported. ZIP members of
+ * supported non-archive types are extracted within archive-safety
+ * limits. PDF pages give only their text layer; no text is recognized
+ * from images, so a PDF without one has no text. Raster images, audio,
+ * video, RAR/7z/tar, and legacy Excel/PowerPoint binaries are
+ * unsupported.
* The media type picks the extractor first; when it is generic, the
* filename and then the representation format do. Both the
* request and response are bounded raw byte streams; source bytes are
diff --git a/contracts/openapi/node-services-internal/openapi.yaml b/contracts/openapi/node-services-internal/openapi.yaml
index fc20e5cd..e4719746 100644
--- a/contracts/openapi/node-services-internal/openapi.yaml
+++ b/contracts/openapi/node-services-internal/openapi.yaml
@@ -832,13 +832,13 @@ paths:
disconnects leaves the line and stops its conversion. Supported
sources include UTF-8 Markdown, plain text, HTML, CSV/TSV, JSON, XML,
YAML and other text, plus PDF, DOC, DOCX, XLSX, PPTX, ZIP/gzip
- archives of those types, SVG, and raster images. ZIP and gzip unwrap
- at most one archive layer; nested ZIP or gzip is unsupported. ZIP
- members of supported non-archive types are extracted within
- archive-safety limits. PDF pages keep their text layer, and pages
- with raster images are also recognized with English and Simplified
- Chinese OCR; raster images are recognized the same way. Audio, video,
- RAR/7z/tar, and legacy Excel/PowerPoint binaries remain unsupported.
+ archives of those types, and SVG. ZIP and gzip unwrap at most one
+ archive layer; nested ZIP or gzip is unsupported. ZIP members of
+ supported non-archive types are extracted within archive-safety
+ limits. PDF pages give only their text layer; no text is recognized
+ from images, so a PDF without one has no text. Raster images, audio,
+ video, RAR/7z/tar, and legacy Excel/PowerPoint binaries are
+ unsupported.
The media type picks the extractor first; when it is generic, the
filename and then the representation format do. Both the
request and response are bounded raw byte streams; source bytes are
@@ -873,8 +873,6 @@ paths:
value: application/vnd.openxmlformats-officedocument.presentationml.presentation
zip:
value: application/zip
- png:
- value: image/png
svg:
value: image/svg+xml
- name: X-Source-Filename
diff --git a/docs/desktop-release.md b/docs/desktop-release.md
index c9e5d9dc..453865f4 100644
--- a/docs/desktop-release.md
+++ b/docs/desktop-release.md
@@ -312,5 +312,5 @@ Node.js into its own folder, removing `com.apple.quarantine` on macOS;
packages and needs no registry. On Linux the services need glibc 2.35
(Ubuntu 22.04, Debian 12), like the PostgreSQL build; with an older glibc the
desktop leaves them out and Native installs from the network. Model data
-(OCR, Voice) is not bundled: Node Services downloads it on first use.
+(Voice) is not bundled: Node Services downloads it on first use.
Intel Macs have none of this and install from the network.
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fde70abc..3d76f889 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -248,15 +248,6 @@ importers:
'@linger/wire-contracts':
specifier: workspace:*
version: link:../../contracts/generated/typescript
- '@napi-rs/canvas':
- specifier: 1.0.5
- version: 1.0.5
- '@tesseract.js-data/chi_sim':
- specifier: 1.0.0
- version: 1.0.0
- '@tesseract.js-data/eng':
- specifier: 1.0.0
- version: 1.0.0
ajv:
specifier: 8.17.1
version: 8.17.1
@@ -287,12 +278,6 @@ importers:
proper-lockfile:
specifier: ^4.1.2
version: 4.1.2
- sharp:
- specifier: 0.35.3
- version: 0.35.3(@types/[email protected])
- tesseract.js-core:
- specifier: 7.0.0
- version: 7.0.0
undici:
specifier: 8.10.0
version: 8.10.0
@@ -3032,12 +3017,6 @@ packages:
'@tanstack/[email protected]':
resolution: {integrity: sha512-bp+v10y65sp2H7WpWfIMyxTNfl8ZVfxFTLRjPIFRryi6FV/J33z4IS53WO4pTk36KlvJ4iLiQz+oaydDC1xbcA==}
- '@tesseract.js-data/[email protected]':
- resolution: {integrity: sha512-iuErURkPbECDUazgsLn/r3c+tU2y5o5S/w14d0A/YiagfsjYyZKgTo75RUpsGJ311qtu0dIX4hqnXAAjmqf2CA==}
-
- '@tesseract.js-data/[email protected]':
- resolution: {integrity: sha512-mbTumm6KQPUHyzTPQaF3ObXYnx0SqqfV2nabqFVQBwD6Kl7PhGSLSzOlfFTWy0P3BjghaSKA2W9GB19Jk+ZcTg==}
-
'@testing-library/[email protected]':
resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}
engines: {node: '>=18'}
@@ -9353,6 +9332,7 @@ snapshots:
'@napi-rs/canvas-linux-x64-musl': 1.0.5
'@napi-rs/canvas-win32-arm64-msvc': 1.0.5
'@napi-rs/canvas-win32-x64-msvc': 1.0.5
+ optional: true
dependencies:
@@ -10205,10 +10185,6 @@ snapshots:
'@tanstack/[email protected]': {}
- '@tesseract.js-data/[email protected]': {}
-
- '@tesseract.js-data/[email protected]': {}
-
'@testing-library/[email protected]':
dependencies:
'@babel/code-frame': 7.29.7
diff --git a/scripts/development-workflow.test.ts b/scripts/development-workflow.test.ts
index 5e6df551..1c96160c 100644
--- a/scripts/development-workflow.test.ts
+++ b/scripts/development-workflow.test.ts
@@ -266,13 +266,7 @@ describe("active product development commands", () => {
const manifest = JSON.parse(
await readRepositoryFile("apps/node-services/package.json"),
);
- for (const name of [
- "tesseract.js-core",
- "@tesseract.js-data/eng",
- "@tesseract.js-data/chi_sim",
- "@napi-rs/canvas",
- "sharp",
- ]) {
+ for (const name of ["pdfjs-dist", "officeparser", "word-extractor"]) {
expect(manifest.dependencies[name]).toMatch(/^\d+\.\d+\.\d+$/);
}
const dockerfile = await readRepositoryFile(
@@ -309,14 +303,11 @@ describe("active product development commands", () => {
expect(nodeServicesPackage.dependencies).toEqual({
"@hocuspocus/server": "^4.3.0",
"@hono/node-server": "^1.19.14",
- "@napi-rs/canvas": "1.0.5",
"@linger/document-files": "workspace:*",
"@linger/document-model": "workspace:*",
"@linger/knowledge-format": "workspace:*",
"@linger/service-kit": "workspace:*",
"@linger/voice-runtime": "workspace:*",
- "@tesseract.js-data/chi_sim": "1.0.0",
- "@tesseract.js-data/eng": "1.0.0",
"@linger/wire-contracts": "workspace:*",
ajv: "8.17.1",
hono: "^4.12.31",
@@ -327,8 +318,6 @@ describe("active product development commands", () => {
"pdfjs-dist": "6.2.108",
openwiki: "0.4.3",
postgres: "3.4.9",
- sharp: "0.35.3",
- "tesseract.js-core": "7.0.0",
"proper-lockfile": "^4.1.2",
"word-extractor": "1.0.4",
undici: "8.10.0",