@intentic/fileq 1.430.0 → 1.431.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/dist/lib/derivers/pdf.d.ts.map +1 -1
- package/dist/lib/derivers/pdf.js +79 -37
- package/dist/lib/derivers/pdf.js.map +1 -1
- package/dist/lib/ocr-slots.d.ts +8 -0
- package/dist/lib/ocr-slots.d.ts.map +1 -0
- package/dist/lib/ocr-slots.js +35 -0
- package/dist/lib/ocr-slots.js.map +1 -0
- package/package.json +7 -7
- package/src/derivers.integration.test.ts +27 -11
- package/src/lib/derivers/image.ts +2 -2
- package/src/lib/derivers/pdf.ts +97 -39
- package/src/lib/ocr-slots.integration.test.ts +64 -0
- package/src/lib/ocr-slots.ts +61 -0
- package/src/lib/sidecar.ts +1 -1
- package/src/skill.ts +3 -3
package/README.md
CHANGED
|
@@ -45,6 +45,12 @@ flowchart LR
|
|
|
45
45
|
500; a rendering that stopped at a lower cap says so in a note, and a run asking for more re-derives it rather than
|
|
46
46
|
taking it from the cache. `fileq stamps` prints each document format's current deriver stamp, so the keeper can
|
|
47
47
|
tell a shadow an upgraded reader, or one newly able to OCR, would write differently.
|
|
48
|
+
- A scan's pages are drawn (pdftoppm, lossless PackBits TIFF, about twelve times faster to write than PNG) and read
|
|
49
|
+
eight at a time, each chunk's drawings removed once read, so a 500-page scan never holds more than eight pages on
|
|
50
|
+
disk. Each `ocr` run takes one of the machine's OCR slots ([src/lib/ocr-slots.ts](src/lib/ocr-slots.ts): flock
|
|
51
|
+
locks in `/tmp`, one per eight cores and per 8 GiB, at most two), since a reader holds about 1.5 GiB and four
|
|
52
|
+
threads and fileq is started by many callers at once: `rg` over six unread scans used to start six readers (7 GiB),
|
|
53
|
+
all of which then ran past their time limit. A text layer is read one page at a time, each page let go once read.
|
|
48
54
|
- `fileq read` on a path the shadow tree refuses (the reference shelf, an agent's worktree) reads it through the
|
|
49
55
|
content cache alone, as it does a file outside the workspace.
|
|
50
56
|
- `fileq check <file>` lints a docx, pptx, xlsx or pdf an agent produced and names each problem where a reader meets
|
|
@@ -86,6 +92,7 @@ way, since only document globs reach the preprocessor.
|
|
|
86
92
|
- [src/app.ts](src/app.ts) — the command routes and the `--help` text an agent reads.
|
|
87
93
|
- [src/lib/derive.ts](src/lib/derive.ts) — `ensureSidecar` and `renderByContent`: the pipeline `read` and `derive` both run.
|
|
88
94
|
- [src/lib/content-cache.ts](src/lib/content-cache.ts) — renderings keyed by content hash and deriver stamp.
|
|
95
|
+
- [src/lib/ocr-slots.ts](src/lib/ocr-slots.ts) — how many OCR readers run at once across the machine.
|
|
89
96
|
- [src/lib/formats.ts](src/lib/formats.ts) — `detectFormat`: magic bytes first, extension as fallback.
|
|
90
97
|
- [src/lib/sidecar.ts](src/lib/sidecar.ts) — sidecar paths, front matter, the freshness rule and the source stat.
|
|
91
98
|
- [bin/fileq-rg-pre](bin/fileq-rg-pre) — ripgrep's preprocessor for documents; `fileq ripgrep-config` wires it.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pdf.d.ts","sourceRoot":"","sources":["../../../src/lib/derivers/pdf.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"pdf.d.ts","sourceRoot":"","sources":["../../../src/lib/derivers/pdf.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAc,OAAO,EAAE,MAAM,cAAc,CAAC;AA0BxD,eAAO,MAAM,UAAU,QAAO,MAG7B,CAAC;AAgBF,eAAO,MAAM,YAAY,QAAO,OAQ/B,CAAC;AA2HF,eAAO,MAAM,UAAU,EAAE,OAiBxB,CAAC"}
|
package/dist/lib/derivers/pdf.js
CHANGED
|
@@ -2,14 +2,16 @@ import { spawnSync } from "node:child_process";
|
|
|
2
2
|
import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { execBounded, ProcessError
|
|
6
|
-
import {
|
|
5
|
+
import { execBounded, ProcessError } from "@intentic/base/process";
|
|
6
|
+
import { getDocumentProxy, getMeta } from "unpdf";
|
|
7
|
+
import { runInOcrSlot } from "../ocr-slots.js";
|
|
7
8
|
import { onPath } from "../tools.js";
|
|
8
9
|
import { stripRunningFurniture } from "./pdf-furniture.js";
|
|
9
10
|
const SCAN_THRESHOLD_CHARS_PER_PAGE = 24;
|
|
10
11
|
const DEFAULT_OCR_PAGES = 20;
|
|
11
12
|
const MAX_OCR_PAGES = 5000;
|
|
12
13
|
const OCR_DPI = "200";
|
|
14
|
+
const OCR_CHUNK_PAGES = 8;
|
|
13
15
|
export const ocrPageCap = () => {
|
|
14
16
|
const asked = Number(process.env["FILEQ_OCR_PAGES"]);
|
|
15
17
|
return Number.isInteger(asked) && asked > 0 ? Math.min(asked, MAX_OCR_PAGES) : DEFAULT_OCR_PAGES;
|
|
@@ -27,30 +29,62 @@ export const ocrAvailable = () => {
|
|
|
27
29
|
return available;
|
|
28
30
|
};
|
|
29
31
|
const readPages = async (images) => {
|
|
30
|
-
const result = await
|
|
32
|
+
const result = await runInOcrSlot("ocr", images, { timeoutMs: ocrTimeoutMs(images.length), maxOutput: 64 * 1024 * 1024 });
|
|
31
33
|
if (!result.timedOut && (result.exitCode === 0 || result.exitCode === 1)) {
|
|
32
34
|
return result.stdout.text;
|
|
33
35
|
}
|
|
34
36
|
throw new ProcessError("ocr", images, result);
|
|
35
37
|
};
|
|
38
|
+
const pageNumberOf = (image) => Number(/-(\d+)\.tif$/.exec(image)?.[1] ?? Number.NaN);
|
|
39
|
+
const recogniseChunk = async (absPath, dir, first, last) => {
|
|
40
|
+
const prefix = join(dir, "page");
|
|
41
|
+
await execBounded("pdftoppm", ["-r", OCR_DPI, "-tiff", "-tiffcompression", "packbits", "-f", String(first), "-l", String(last), absPath, prefix], {
|
|
42
|
+
timeoutMs: 60_000 + (last - first + 1) * 2_000,
|
|
43
|
+
});
|
|
44
|
+
const images = (await readdir(dir)).filter((name) => name.endsWith(".tif")).toSorted((a, b) => pageNumberOf(a) - pageNumberOf(b));
|
|
45
|
+
try {
|
|
46
|
+
const text = images.length === 0 ? [] : (await readPages(images.map((image) => join(dir, image)))).split("\f");
|
|
47
|
+
const pages = Array.from({ length: last - first + 1 }, () => "");
|
|
48
|
+
for (const [index, image] of images.entries()) {
|
|
49
|
+
const page = pageNumberOf(image) - first;
|
|
50
|
+
if (page >= 0 && page < pages.length) {
|
|
51
|
+
pages[page] = (text[index] ?? "").replaceAll(/[ \t]+/g, " ").trim();
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return pages;
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
await Promise.all(images.map((image) => rm(join(dir, image), { force: true })));
|
|
58
|
+
}
|
|
59
|
+
};
|
|
36
60
|
const recognisePages = async (absPath, totalPages, cap) => {
|
|
37
61
|
const dir = await mkdtemp(join(tmpdir(), "fileq-ocr-"));
|
|
38
62
|
const last = Math.min(totalPages, cap);
|
|
39
63
|
try {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const images = (await readdir(dir)).filter((name) => name.endsWith(".png")).toSorted();
|
|
44
|
-
if (images.length === 0) {
|
|
45
|
-
return [];
|
|
64
|
+
const pages = [];
|
|
65
|
+
for (let first = 1; first <= last; first += OCR_CHUNK_PAGES) {
|
|
66
|
+
pages.push(...(await recogniseChunk(absPath, dir, first, Math.min(last, first + OCR_CHUNK_PAGES - 1))));
|
|
46
67
|
}
|
|
47
|
-
|
|
48
|
-
return images.map((_, index) => (pages[index] ?? "").replaceAll(/[ \t]+/g, " ").trim());
|
|
68
|
+
return pages;
|
|
49
69
|
}
|
|
50
70
|
finally {
|
|
51
71
|
await rm(dir, { recursive: true, force: true });
|
|
52
72
|
}
|
|
53
73
|
};
|
|
74
|
+
const pageTexts = async (pdf) => {
|
|
75
|
+
const pages = [];
|
|
76
|
+
for (let number = 1; number <= pdf.numPages; number++) {
|
|
77
|
+
const page = await pdf.getPage(number);
|
|
78
|
+
const content = await page.getTextContent();
|
|
79
|
+
pages.push(content.items
|
|
80
|
+
.map((item) => ("str" in item ? item.str + (item.hasEOL ? "\n" : "") : ""))
|
|
81
|
+
.join("")
|
|
82
|
+
.replaceAll(/[ \t]+/g, " ")
|
|
83
|
+
.trim());
|
|
84
|
+
page.cleanup();
|
|
85
|
+
}
|
|
86
|
+
return pages;
|
|
87
|
+
};
|
|
54
88
|
const pagesToMarkdown = (pages) => pages.length === 1
|
|
55
89
|
? (pages[0] ?? "")
|
|
56
90
|
: pages.map((page, index) => `## Page ${index + 1}\n\n${page === "" ? "(no text on this page)" : page}`).join("\n\n");
|
|
@@ -63,6 +97,35 @@ const withoutFurniture = (pages) => {
|
|
|
63
97
|
const { pages: kept, removed, example } = stripRunningFurniture(pages);
|
|
64
98
|
return { markdown: pagesToMarkdown(kept), notes: furnitureNotes(removed, example) };
|
|
65
99
|
};
|
|
100
|
+
const derivePdf = async (absPath, pdf) => {
|
|
101
|
+
const totalPages = pdf.numPages;
|
|
102
|
+
const pages = await pageTexts(pdf);
|
|
103
|
+
const meta = await getMeta(pdf).catch(() => undefined);
|
|
104
|
+
const info = meta?.info;
|
|
105
|
+
const title = typeof info?.["Title"] === "string" && info["Title"] !== "" ? info["Title"] : undefined;
|
|
106
|
+
const totalChars = pages.reduce((sum, page) => sum + page.length, 0);
|
|
107
|
+
if (totalChars < SCAN_THRESHOLD_CHARS_PER_PAGE * totalPages) {
|
|
108
|
+
const plural = totalPages === 1 ? "" : "s";
|
|
109
|
+
if (!ocrAvailable()) {
|
|
110
|
+
return {
|
|
111
|
+
markdown: "",
|
|
112
|
+
title,
|
|
113
|
+
notes: [`no usable text layer across ${totalPages} page${plural} (a scan?): OCR is not part of this tier`],
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
const cap = ocrPageCap();
|
|
117
|
+
const recognised = await recognisePages(absPath, totalPages, cap);
|
|
118
|
+
const notes = [
|
|
119
|
+
`scanned: text recognised by OCR (PaddleOCR) on ${recognised.length} of ${totalPages} page${plural} — recognised, not exact; check figures against the page image`,
|
|
120
|
+
];
|
|
121
|
+
if (totalPages > cap) {
|
|
122
|
+
notes.push(capNote(cap));
|
|
123
|
+
}
|
|
124
|
+
const { markdown, notes: stripped } = withoutFurniture(recognised);
|
|
125
|
+
return { markdown, title, notes: [...notes, ...stripped] };
|
|
126
|
+
}
|
|
127
|
+
return { title, ...withoutFurniture(pages) };
|
|
128
|
+
};
|
|
66
129
|
export const pdfDeriver = {
|
|
67
130
|
get name() {
|
|
68
131
|
return ocrAvailable() ? "pdf+ppocr" : "pdf";
|
|
@@ -70,33 +133,12 @@ export const pdfDeriver = {
|
|
|
70
133
|
version: 2,
|
|
71
134
|
derive: async (absPath) => {
|
|
72
135
|
const pdf = await getDocumentProxy(new Uint8Array(await readFile(absPath)));
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
const totalChars = pages.reduce((sum, page) => sum + page.length, 0);
|
|
79
|
-
if (totalChars < SCAN_THRESHOLD_CHARS_PER_PAGE * totalPages) {
|
|
80
|
-
const plural = totalPages === 1 ? "" : "s";
|
|
81
|
-
if (!ocrAvailable()) {
|
|
82
|
-
return {
|
|
83
|
-
markdown: "",
|
|
84
|
-
title,
|
|
85
|
-
notes: [`no usable text layer across ${totalPages} page${plural} (a scan?): OCR is not part of this tier`],
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
const cap = ocrPageCap();
|
|
89
|
-
const recognised = await recognisePages(absPath, totalPages, cap);
|
|
90
|
-
const notes = [
|
|
91
|
-
`scanned: text recognised by OCR (PaddleOCR) on ${recognised.length} of ${totalPages} page${plural} — recognised, not exact; check figures against the page image`,
|
|
92
|
-
];
|
|
93
|
-
if (totalPages > cap) {
|
|
94
|
-
notes.push(capNote(cap));
|
|
95
|
-
}
|
|
96
|
-
const { markdown, notes: stripped } = withoutFurniture(recognised);
|
|
97
|
-
return { markdown, title, notes: [...notes, ...stripped] };
|
|
136
|
+
try {
|
|
137
|
+
return await derivePdf(absPath, pdf);
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
await pdf.loadingTask.destroy();
|
|
98
141
|
}
|
|
99
|
-
return { title, ...withoutFurniture(pages) };
|
|
100
142
|
},
|
|
101
143
|
};
|
|
102
144
|
//# sourceMappingURL=pdf.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pdf.js","sourceRoot":"","sources":["../../../src/lib/derivers/pdf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"pdf.js","sourceRoot":"","sources":["../../../src/lib/derivers/pdf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;A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AAC;IACL,CAAC;CACJ,CAAC"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type ProcessResult, type RunOptions } from "@intentic/base/process";
|
|
2
|
+
export declare const ocrSlotCount: (cores?: number, memoryBytes?: number) => number;
|
|
3
|
+
export interface SlotOptions extends RunOptions {
|
|
4
|
+
readonly slots?: number;
|
|
5
|
+
readonly lockDir?: string;
|
|
6
|
+
}
|
|
7
|
+
export declare const runInOcrSlot: (command: string, args: readonly string[], options?: SlotOptions) => Promise<ProcessResult>;
|
|
8
|
+
//# sourceMappingURL=ocr-slots.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ocr-slots.d.ts","sourceRoot":"","sources":["../../src/lib/ocr-slots.ts"],"names":[],"mappings":"AAGA,OAAO,EAAc,KAAK,aAAa,EAAE,KAAK,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAmBzF,eAAO,MAAM,YAAY,WAAW,MAAM,gBAAwC,MAAM,KAAgB,MACU,CAAC;AAEnH,MAAM,WAAW,WAAY,SAAQ,UAAU;IAC3C,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAExB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC7B;AASD,eAAO,MAAM,YAAY,YAAmB,MAAM,QAAQ,SAAS,MAAM,EAAE,YAAW,WAAW,KAAQ,OAAO,CAAC,aAAa,CAsB7H,CAAC"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { availableParallelism, tmpdir, totalmem } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { sleep } from "@intentic/base/async";
|
|
4
|
+
import { runBounded } from "@intentic/base/process";
|
|
5
|
+
import { onPath } from "./tools.js";
|
|
6
|
+
const CORES_PER_SLOT = 8;
|
|
7
|
+
const BYTES_PER_SLOT = 8 * 1024 ** 3;
|
|
8
|
+
const MAX_SLOTS = 2;
|
|
9
|
+
const BUSY = 75;
|
|
10
|
+
const POLL_FIRST_MS = 250;
|
|
11
|
+
const POLL_MAX_MS = 2_000;
|
|
12
|
+
export const ocrSlotCount = (cores = availableParallelism(), memoryBytes = totalmem()) => Math.max(1, Math.min(MAX_SLOTS, Math.floor(cores / CORES_PER_SLOT), Math.floor(memoryBytes / BYTES_PER_SLOT)));
|
|
13
|
+
const lockDirOf = (options) => options.lockDir ?? (process.platform === "win32" ? tmpdir() : "/tmp");
|
|
14
|
+
export const runInOcrSlot = async (command, args, options = {}) => {
|
|
15
|
+
if (!onPath("flock")) {
|
|
16
|
+
return runBounded(command, args, options);
|
|
17
|
+
}
|
|
18
|
+
const slots = options.slots ?? ocrSlotCount();
|
|
19
|
+
const dir = lockDirOf(options);
|
|
20
|
+
for (let wait = POLL_FIRST_MS;; wait = Math.min(wait * 2, POLL_MAX_MS)) {
|
|
21
|
+
for (let slot = 0; slot < slots; slot++) {
|
|
22
|
+
const lock = join(dir, `fileq-ocr-${String(slot)}.lock`);
|
|
23
|
+
const result = await runBounded("flock", ["--no-fork", "--nonblock", "--conflict-exit-code", String(BUSY), lock, command, ...args], options);
|
|
24
|
+
if (result.exitCode === BUSY) {
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
if (result.exitCode !== null && result.exitCode >= 64 && result.stdout.text === "") {
|
|
28
|
+
return runBounded(command, args, options);
|
|
29
|
+
}
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
await sleep(wait, { signal: options.signal });
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
//# sourceMappingURL=ocr-slots.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ocr-slots.js","sourceRoot":"","sources":["../../src/lib/ocr-slots.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACjE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAE,M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AK,IAAI,IAAI,GAAG,aAAa,GAAI,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,EAAE,WAAW,CAAC,EAAE,CAAC;QACtE,KAAK,IAAI,IAAI,GAAG,CAAC,EAAE,IAAI,GAAG,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC;YACtC,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,aAAa,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACzD,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,OAAO,EAAE,CAAC,WAAW,EAAE,YAAY,EAAE,sBAAsB,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;YAC7I,IAAI,MAAM,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC;gBAC3B,SAAS;YACb,CAAC;YAED,IAAI,MAAM,CAAC,QAAQ,KAAK,IAAI,IAAI,MAAM,CAAC,QAAQ,IAAI,EAAE,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,EAAE,EAAE,CAAC;gBACjF,OAAO,UAAU,CAAC,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;YAC9C,CAAC;YAED,OAAO,MAAM,CAAC;QAClB,CAAC;QACD,MAAM,KAAK,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAClD,CAAC;AACL,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intentic/fileq",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.431.0",
|
|
4
4
|
"description": "fileq, agent-native file reading: any binary workspace file (docx, xlsx, pptx, pdf, images, audio, archives) as clean budgeted markdown, cached by content so a repeat read is instant",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
9
9
|
"url": "git+https://github.com/intentic/intentic.git",
|
|
10
|
-
"directory": "
|
|
10
|
+
"directory": "_agent-tools/fileq"
|
|
11
11
|
},
|
|
12
12
|
"files": [
|
|
13
13
|
"bin",
|
|
@@ -73,11 +73,11 @@
|
|
|
73
73
|
}
|
|
74
74
|
},
|
|
75
75
|
"dependencies": {
|
|
76
|
-
"@intentic/agent-cli": "1.
|
|
77
|
-
"@intentic/base": "1.
|
|
78
|
-
"@intentic/constants": "1.
|
|
79
|
-
"@intentic/webq": "1.
|
|
80
|
-
"@intentic/workspace-ignore": "1.
|
|
76
|
+
"@intentic/agent-cli": "1.431.0",
|
|
77
|
+
"@intentic/base": "1.431.0",
|
|
78
|
+
"@intentic/constants": "1.431.0",
|
|
79
|
+
"@intentic/webq": "1.431.0",
|
|
80
|
+
"@intentic/workspace-ignore": "1.431.0",
|
|
81
81
|
"@stricli/core": "1.3.0",
|
|
82
82
|
"exifr": "7.1.3",
|
|
83
83
|
"fflate": "0.8.3",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/* Every deriver against a real file its real parser accepts, in a temp tree. */
|
|
2
2
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
3
|
-
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { requires } from "@intentic/testing/requires";
|
|
@@ -142,6 +142,7 @@ describe("pdf", () => {
|
|
|
142
142
|
// A stand-in `ocr` on PATH, speaking the real one's protocol (_sandbox/ocr/src/cli.ts): `--check` answers
|
|
143
143
|
// whether it can read, and a run prints each image's text with a form feed line between images, leaving an image
|
|
144
144
|
// it could not read empty and exiting 1.
|
|
145
|
+
// Each run also logs how many images it was handed and how many drawings sat beside them, to `runs.log` in its bin.
|
|
145
146
|
const standIn = (check: number): string => {
|
|
146
147
|
const bin = mkdtempSync(join(tmpdir(), "fileq-ocr-bin-"));
|
|
147
148
|
writeFileSync(
|
|
@@ -149,14 +150,15 @@ describe("pdf", () => {
|
|
|
149
150
|
[
|
|
150
151
|
"#!/bin/sh",
|
|
151
152
|
`if [ "$1" = "--check" ]; then exit ${check}; fi`,
|
|
153
|
+
`echo "$# $(ls "$(dirname "$1")" | wc -l)" >> ${bin}/runs.log`,
|
|
152
154
|
"status=0",
|
|
153
155
|
"first=1",
|
|
154
156
|
'for image in "$@"; do',
|
|
155
157
|
" [ $first = 1 ] || printf '\\f\\n'",
|
|
156
158
|
" first=0",
|
|
157
159
|
' case "$image" in',
|
|
158
|
-
" *page-1.
|
|
159
|
-
' *) printf \'TOTAL DUE ON %s\\n\' "$(basename "$image" .
|
|
160
|
+
" *page-1.tif) status=1 ;;",
|
|
161
|
+
' *) printf \'TOTAL DUE ON %s\\n\' "$(basename "$image" .tif)" ;;',
|
|
160
162
|
" esac",
|
|
161
163
|
"done",
|
|
162
164
|
"exit $status",
|
|
@@ -166,43 +168,57 @@ describe("pdf", () => {
|
|
|
166
168
|
);
|
|
167
169
|
return bin;
|
|
168
170
|
};
|
|
169
|
-
const
|
|
171
|
+
const runsOf = (bin: string): string[] => readFileSync(join(bin, "runs.log"), "utf8").trim().split("\n");
|
|
172
|
+
const withPath = async <T>(bin: string, body: (bin: string) => Promise<T>): Promise<T> => {
|
|
170
173
|
const previousPath = process.env["PATH"];
|
|
171
174
|
process.env["PATH"] = `${bin}:${previousPath ?? ""}`;
|
|
172
175
|
try {
|
|
173
|
-
return await body();
|
|
176
|
+
return await body(bin);
|
|
174
177
|
} finally {
|
|
175
178
|
process.env["PATH"] = previousPath;
|
|
176
179
|
rmSync(bin, { recursive: true, force: true });
|
|
177
180
|
}
|
|
178
181
|
};
|
|
179
|
-
// A two
|
|
180
|
-
const scan = (name: string): string => {
|
|
182
|
+
// A scan, two pages unless asked for more, drawn by Pillow: pages of pixels, no text layer.
|
|
183
|
+
const scan = (name: string, pages = 2): string => {
|
|
181
184
|
const path = join(root, name);
|
|
182
185
|
execFileSync("python3", [
|
|
183
186
|
"-c",
|
|
184
187
|
[
|
|
185
188
|
"import sys",
|
|
186
189
|
"from PIL import Image, ImageDraw",
|
|
187
|
-
"pages = [Image.new('RGB', (850, 1100), 'white') for _ in range(2)]",
|
|
190
|
+
"pages = [Image.new('RGB', (850, 1100), 'white') for _ in range(int(sys.argv[2]))]",
|
|
188
191
|
"for page in pages: ImageDraw.Draw(page).rectangle((100, 100, 700, 160), fill='black')",
|
|
189
192
|
"pages[0].save(sys.argv[1], save_all=True, append_images=pages[1:], resolution=100.0)",
|
|
190
193
|
].join("\n"),
|
|
191
194
|
path,
|
|
195
|
+
String(pages),
|
|
192
196
|
]);
|
|
193
197
|
return path;
|
|
194
198
|
};
|
|
195
199
|
|
|
196
200
|
/* fileq's half of the OCR tier, wherever poppler and Pillow are (ci-base carries both): the pages drawn and handed
|
|
197
|
-
to `ocr`
|
|
201
|
+
to `ocr` a chunk at a time, each page keeping its own text, an unreadable page left empty in its place. */
|
|
198
202
|
const poppler = requires(onPath("pdftoppm") && pillow(), "pdftoppm on PATH and python3 with Pillow");
|
|
199
|
-
test.skipIf(!poppler.runs)(poppler.title("a scan's pages go to ocr
|
|
203
|
+
test.skipIf(!poppler.runs)(poppler.title("a scan's pages go to ocr together, and each keeps its own text"), async () => {
|
|
200
204
|
const path = scan("two-pages.pdf");
|
|
201
|
-
await withPath(standIn(0), async () => {
|
|
205
|
+
await withPath(standIn(0), async (bin) => {
|
|
202
206
|
expect(pdfDeriver.name).toBe("pdf+ppocr");
|
|
203
207
|
const doc = await pdfDeriver.derive(path);
|
|
204
208
|
expect(doc.markdown).toBe("## Page 1\n\n(no text on this page)\n\n## Page 2\n\nTOTAL DUE ON page-2");
|
|
205
209
|
expect(doc.notes.join(" ")).toContain("recognised by OCR (PaddleOCR) on 2 of 2 pages");
|
|
210
|
+
expect(runsOf(bin)).toEqual(["2 2"]);
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
test.skipIf(!poppler.runs)(poppler.title("a long scan is read eight pages a run, in order, with one chunk's drawings on disk at a time"), async () => {
|
|
215
|
+
const path = scan("eleven-pages.pdf", 11);
|
|
216
|
+
await withPath(standIn(0), async (bin) => {
|
|
217
|
+
const doc = await pdfDeriver.derive(path);
|
|
218
|
+
const pageTexts = [...doc.markdown.matchAll(/^TOTAL DUE ON (page-\d+)$/gm)].map((match) => match[1]);
|
|
219
|
+
expect(pageTexts).toEqual(Array.from({ length: 11 }, (_, index) => `page-${String(index + 1).padStart(2, "0")}`));
|
|
220
|
+
expect(doc.markdown).toContain("## Page 11\n\nTOTAL DUE ON page-11");
|
|
221
|
+
expect(runsOf(bin)).toEqual(["8 8", "3 3"]);
|
|
206
222
|
});
|
|
207
223
|
});
|
|
208
224
|
|
|
@@ -4,8 +4,8 @@ import { imageSize } from "image-size";
|
|
|
4
4
|
import type { DerivedDoc, Deriver } from "./deriver.js";
|
|
5
5
|
|
|
6
6
|
// exifr is CommonJS behind a `main` field with no exports map, so a named `import { parse }` type-checks but throws at
|
|
7
|
-
// load; the default import is its module.exports under Node and under a bundler alike (the
|
|
8
|
-
// fileq, and
|
|
7
|
+
// load; the default import is its module.exports under Node and under a bundler alike (the desktop app's compiled file server
|
|
8
|
+
// bundles fileq, and a `createRequire` call is the one form a bundle cannot
|
|
9
9
|
// follow: there it failed every derive with "Cannot find module 'exifr'").
|
|
10
10
|
// oxlint-disable-next-line import/no-named-as-default-member -- the named import this rule asks for is the one that throws at load.
|
|
11
11
|
const { parse: parseExif } = exifr;
|
package/src/lib/derivers/pdf.ts
CHANGED
|
@@ -2,8 +2,9 @@ import { spawnSync } from "node:child_process";
|
|
|
2
2
|
import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { execBounded, ProcessError
|
|
6
|
-
import {
|
|
5
|
+
import { execBounded, ProcessError } from "@intentic/base/process";
|
|
6
|
+
import { getDocumentProxy, getMeta } from "unpdf";
|
|
7
|
+
import { runInOcrSlot } from "../ocr-slots.js";
|
|
7
8
|
import { onPath } from "../tools.js";
|
|
8
9
|
import type { DerivedDoc, Deriver } from "./deriver.js";
|
|
9
10
|
import { stripRunningFurniture } from "./pdf-furniture.js";
|
|
@@ -24,6 +25,11 @@ const SCAN_THRESHOLD_CHARS_PER_PAGE = 24;
|
|
|
24
25
|
const DEFAULT_OCR_PAGES = 20;
|
|
25
26
|
const MAX_OCR_PAGES = 5000;
|
|
26
27
|
const OCR_DPI = "200";
|
|
28
|
+
// Pages drawn and read this many at a time. The drawings on disk stay one chunk's worth (all 500 at once were about
|
|
29
|
+
// 900 MB of PNG in /tmp), each reader process ends after its chunk, and the machine's OCR slot (ocr-slots.ts) is let
|
|
30
|
+
// go between chunks, so a read waiting behind a 500-page scan waits for one chunk of it. Starting a reader costs about
|
|
31
|
+
// half a second against several seconds a page.
|
|
32
|
+
const OCR_CHUNK_PAGES = 8;
|
|
27
33
|
|
|
28
34
|
/** How many pages of a scan this run recognises: FILEQ_OCR_PAGES when it is a sane count, else 20. */
|
|
29
35
|
export const ocrPageCap = (): number => {
|
|
@@ -57,34 +63,77 @@ export const ocrAvailable = (): boolean => {
|
|
|
57
63
|
|
|
58
64
|
// What `ocr` printed for its images, one page per image: it writes a form feed line between images, and an image it
|
|
59
65
|
// could not read leaves its page empty (exit 1) rather than shifting the ones after it. The pages are split on those
|
|
60
|
-
// form feeds, so the cap stays well past what
|
|
66
|
+
// form feeds, so the cap stays well past what a chunk of pages comes to: a cut middle would shift every page after it.
|
|
61
67
|
const readPages = async (images: readonly string[]): Promise<string> => {
|
|
62
|
-
const result = await
|
|
68
|
+
const result = await runInOcrSlot("ocr", images, { timeoutMs: ocrTimeoutMs(images.length), maxOutput: 64 * 1024 * 1024 });
|
|
63
69
|
if (!result.timedOut && (result.exitCode === 0 || result.exitCode === 1)) {
|
|
64
70
|
return result.stdout.text;
|
|
65
71
|
}
|
|
66
72
|
throw new ProcessError("ocr", images, result);
|
|
67
73
|
};
|
|
68
74
|
|
|
75
|
+
// The page a drawing is of, off the number pdftoppm puts in its name (`page-07.tif`).
|
|
76
|
+
const pageNumberOf = (image: string): number => Number(/-(\d+)\.tif$/.exec(image)?.[1] ?? Number.NaN);
|
|
77
|
+
|
|
78
|
+
// Pages `first` to `last` drawn and read, one entry per page whether or not it could be drawn, and the drawings
|
|
79
|
+
// removed. TIFF with PackBits is as lossless as PNG, so the reader sees the same pixels and reads the same text, but
|
|
80
|
+
// pdftoppm writes it about twelve times faster: PNG's compression cost 0.85 s a page at 200 dpi (measured 2026-11-23).
|
|
81
|
+
const recogniseChunk = async (absPath: string, dir: string, first: number, last: number): Promise<string[]> => {
|
|
82
|
+
const prefix = join(dir, "page");
|
|
83
|
+
await execBounded("pdftoppm", ["-r", OCR_DPI, "-tiff", "-tiffcompression", "packbits", "-f", String(first), "-l", String(last), absPath, prefix], {
|
|
84
|
+
timeoutMs: 60_000 + (last - first + 1) * 2_000,
|
|
85
|
+
});
|
|
86
|
+
const images = (await readdir(dir)).filter((name) => name.endsWith(".tif")).toSorted((a, b) => pageNumberOf(a) - pageNumberOf(b));
|
|
87
|
+
try {
|
|
88
|
+
const text = images.length === 0 ? [] : (await readPages(images.map((image) => join(dir, image)))).split("\f");
|
|
89
|
+
const pages = Array.from({ length: last - first + 1 }, () => "");
|
|
90
|
+
for (const [index, image] of images.entries()) {
|
|
91
|
+
const page = pageNumberOf(image) - first;
|
|
92
|
+
if (page >= 0 && page < pages.length) {
|
|
93
|
+
pages[page] = (text[index] ?? "").replaceAll(/[ \t]+/g, " ").trim();
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return pages;
|
|
97
|
+
} finally {
|
|
98
|
+
await Promise.all(images.map((image) => rm(join(dir, image), { force: true })));
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
69
102
|
const recognisePages = async (absPath: string, totalPages: number, cap: number): Promise<string[]> => {
|
|
70
103
|
const dir = await mkdtemp(join(tmpdir(), "fileq-ocr-"));
|
|
71
104
|
const last = Math.min(totalPages, cap);
|
|
72
105
|
try {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
const images = (await readdir(dir)).filter((name) => name.endsWith(".png")).toSorted();
|
|
77
|
-
if (images.length === 0) {
|
|
78
|
-
return [];
|
|
106
|
+
const pages: string[] = [];
|
|
107
|
+
for (let first = 1; first <= last; first += OCR_CHUNK_PAGES) {
|
|
108
|
+
pages.push(...(await recogniseChunk(absPath, dir, first, Math.min(last, first + OCR_CHUNK_PAGES - 1))));
|
|
79
109
|
}
|
|
80
|
-
|
|
81
|
-
const pages = (await readPages(images.map((image) => join(dir, image)))).split("\f");
|
|
82
|
-
return images.map((_, index) => (pages[index] ?? "").replaceAll(/[ \t]+/g, " ").trim());
|
|
110
|
+
return pages;
|
|
83
111
|
} finally {
|
|
84
112
|
await rm(dir, { recursive: true, force: true });
|
|
85
113
|
}
|
|
86
114
|
};
|
|
87
115
|
|
|
116
|
+
type PdfDocument = Awaited<ReturnType<typeof getDocumentProxy>>;
|
|
117
|
+
|
|
118
|
+
// Each page's text, one page at a time and each let go once read: unpdf's extractText asks for every page at once,
|
|
119
|
+
// and pdf.js holds them all until the end (a 5000-page text pdf peaked at 699 MB that way, 286 MB this way).
|
|
120
|
+
const pageTexts = async (pdf: PdfDocument): Promise<string[]> => {
|
|
121
|
+
const pages: string[] = [];
|
|
122
|
+
for (let number = 1; number <= pdf.numPages; number++) {
|
|
123
|
+
const page = await pdf.getPage(number);
|
|
124
|
+
const content = await page.getTextContent();
|
|
125
|
+
pages.push(
|
|
126
|
+
content.items
|
|
127
|
+
.map((item) => ("str" in item ? item.str + (item.hasEOL ? "\n" : "") : ""))
|
|
128
|
+
.join("")
|
|
129
|
+
.replaceAll(/[ \t]+/g, " ")
|
|
130
|
+
.trim(),
|
|
131
|
+
);
|
|
132
|
+
page.cleanup();
|
|
133
|
+
}
|
|
134
|
+
return pages;
|
|
135
|
+
};
|
|
136
|
+
|
|
88
137
|
const pagesToMarkdown = (pages: readonly string[]): string =>
|
|
89
138
|
pages.length === 1
|
|
90
139
|
? (pages[0] ?? "")
|
|
@@ -103,6 +152,36 @@ const withoutFurniture = (pages: readonly string[]): { markdown: string; notes:
|
|
|
103
152
|
return { markdown: pagesToMarkdown(kept), notes: furnitureNotes(removed, example) };
|
|
104
153
|
};
|
|
105
154
|
|
|
155
|
+
const derivePdf = async (absPath: string, pdf: PdfDocument): Promise<DerivedDoc> => {
|
|
156
|
+
const totalPages = pdf.numPages;
|
|
157
|
+
const pages = await pageTexts(pdf);
|
|
158
|
+
const meta = await getMeta(pdf).catch(() => undefined);
|
|
159
|
+
const info = meta?.info as Record<string, unknown> | undefined;
|
|
160
|
+
const title = typeof info?.["Title"] === "string" && info["Title"] !== "" ? info["Title"] : undefined;
|
|
161
|
+
const totalChars = pages.reduce((sum, page) => sum + page.length, 0);
|
|
162
|
+
if (totalChars < SCAN_THRESHOLD_CHARS_PER_PAGE * totalPages) {
|
|
163
|
+
const plural = totalPages === 1 ? "" : "s";
|
|
164
|
+
if (!ocrAvailable()) {
|
|
165
|
+
return {
|
|
166
|
+
markdown: "",
|
|
167
|
+
title,
|
|
168
|
+
notes: [`no usable text layer across ${totalPages} page${plural} (a scan?): OCR is not part of this tier`],
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
const cap = ocrPageCap();
|
|
172
|
+
const recognised = await recognisePages(absPath, totalPages, cap);
|
|
173
|
+
const notes = [
|
|
174
|
+
`scanned: text recognised by OCR (PaddleOCR) on ${recognised.length} of ${totalPages} page${plural} — recognised, not exact; check figures against the page image`,
|
|
175
|
+
];
|
|
176
|
+
if (totalPages > cap) {
|
|
177
|
+
notes.push(capNote(cap));
|
|
178
|
+
}
|
|
179
|
+
const { markdown, notes: stripped } = withoutFurniture(recognised);
|
|
180
|
+
return { markdown, title, notes: [...notes, ...stripped] };
|
|
181
|
+
}
|
|
182
|
+
return { title, ...withoutFurniture(pages) };
|
|
183
|
+
};
|
|
184
|
+
|
|
106
185
|
export const pdfDeriver: Deriver = {
|
|
107
186
|
// The stamp names OCR capability, since a sidecar written before the reader was available must read as stale now
|
|
108
187
|
// that it's here. A static name would leave a pre-OCR sidecar looking current forever. It names the reader too:
|
|
@@ -113,32 +192,11 @@ export const pdfDeriver: Deriver = {
|
|
|
113
192
|
version: 2,
|
|
114
193
|
derive: async (absPath): Promise<DerivedDoc> => {
|
|
115
194
|
const pdf = await getDocumentProxy(new Uint8Array(await readFile(absPath)));
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
const totalChars = pages.reduce((sum, page) => sum + page.length, 0);
|
|
122
|
-
if (totalChars < SCAN_THRESHOLD_CHARS_PER_PAGE * totalPages) {
|
|
123
|
-
const plural = totalPages === 1 ? "" : "s";
|
|
124
|
-
if (!ocrAvailable()) {
|
|
125
|
-
return {
|
|
126
|
-
markdown: "",
|
|
127
|
-
title,
|
|
128
|
-
notes: [`no usable text layer across ${totalPages} page${plural} (a scan?): OCR is not part of this tier`],
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
const cap = ocrPageCap();
|
|
132
|
-
const recognised = await recognisePages(absPath, totalPages, cap);
|
|
133
|
-
const notes = [
|
|
134
|
-
`scanned: text recognised by OCR (PaddleOCR) on ${recognised.length} of ${totalPages} page${plural} — recognised, not exact; check figures against the page image`,
|
|
135
|
-
];
|
|
136
|
-
if (totalPages > cap) {
|
|
137
|
-
notes.push(capNote(cap));
|
|
138
|
-
}
|
|
139
|
-
const { markdown, notes: stripped } = withoutFurniture(recognised);
|
|
140
|
-
return { markdown, title, notes: [...notes, ...stripped] };
|
|
195
|
+
// One fileq run derives a batch of files, so each document is let go before the next.
|
|
196
|
+
try {
|
|
197
|
+
return await derivePdf(absPath, pdf);
|
|
198
|
+
} finally {
|
|
199
|
+
await pdf.loadingTask.destroy();
|
|
141
200
|
}
|
|
142
|
-
return { title, ...withoutFurniture(pages) };
|
|
143
201
|
},
|
|
144
202
|
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/* The machine-wide OCR slots: flock locks in a directory every process shares. */
|
|
2
|
+
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { requires } from "@intentic/testing/requires";
|
|
6
|
+
import { ocrSlotCount, runInOcrSlot } from "./ocr-slots.js";
|
|
7
|
+
import { onPath } from "./tools.js";
|
|
8
|
+
|
|
9
|
+
let dir: string;
|
|
10
|
+
beforeEach(() => {
|
|
11
|
+
dir = mkdtempSync(join(tmpdir(), "fileq-ocr-slots-"));
|
|
12
|
+
});
|
|
13
|
+
afterEach(() => {
|
|
14
|
+
rmSync(dir, { recursive: true, force: true });
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
describe("ocrSlotCount", () => {
|
|
18
|
+
test("one slot per eight cores and per 8 GiB, never none and never more than two", () => {
|
|
19
|
+
expect(ocrSlotCount(4, 64 * 1024 ** 3)).toBe(1);
|
|
20
|
+
expect(ocrSlotCount(16, 64 * 1024 ** 3)).toBe(2);
|
|
21
|
+
expect(ocrSlotCount(64, 256 * 1024 ** 3)).toBe(2);
|
|
22
|
+
expect(ocrSlotCount(16, 12 * 1024 ** 3)).toBe(1);
|
|
23
|
+
expect(ocrSlotCount(1, 1024 ** 3)).toBe(1);
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe("runInOcrSlot", () => {
|
|
28
|
+
const flock = requires(onPath("flock"), "flock (util-linux) on PATH");
|
|
29
|
+
// Each run notes when it starts and ends in one shared log, so overlapping runs interleave there.
|
|
30
|
+
const run = (name: string, slots: number) =>
|
|
31
|
+
runInOcrSlot("sh", ["-c", `echo "start ${name}" >> ${dir}/log; sleep 0.4; echo "end ${name}" >> ${dir}/log; echo done ${name}`], {
|
|
32
|
+
slots,
|
|
33
|
+
lockDir: dir,
|
|
34
|
+
timeoutMs: 30_000,
|
|
35
|
+
});
|
|
36
|
+
const log = (): string[] => readFileSync(join(dir, "log"), "utf8").trim().split("\n");
|
|
37
|
+
|
|
38
|
+
test.skipIf(!flock.runs)(flock.title("with one slot, a second run waits for the first to end"), async () => {
|
|
39
|
+
const [first, second] = await Promise.all([run("a", 1), run("b", 1)]);
|
|
40
|
+
expect(first.stdout.text).toBe("done a\n");
|
|
41
|
+
expect(second.stdout.text).toBe("done b\n");
|
|
42
|
+
const lines = log();
|
|
43
|
+
expect(lines).toHaveLength(4);
|
|
44
|
+
expect(lines[0]?.replace(/ .$/, "")).toBe("start");
|
|
45
|
+
expect(lines[1]).toBe(lines[0]?.replace("start", "end"));
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test.skipIf(!flock.runs)(flock.title("with two slots, two runs go at once"), async () => {
|
|
49
|
+
await Promise.all([run("a", 2), run("b", 2)]);
|
|
50
|
+
expect(log().map((line) => line.split(" ")[0])).toEqual(["start", "start", "end", "end"]);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test.skipIf(!flock.runs)(flock.title("the command's own exit code and output come back"), async () => {
|
|
54
|
+
const result = await runInOcrSlot("sh", ["-c", "echo read; exit 1"], { slots: 1, lockDir: dir, timeoutMs: 30_000 });
|
|
55
|
+
expect(result.exitCode).toBe(1);
|
|
56
|
+
expect(result.stdout.text).toBe("read\n");
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test.skipIf(!flock.runs)(flock.title("a lock directory flock cannot use costs the slot, not the run"), async () => {
|
|
60
|
+
const result = await runInOcrSlot("sh", ["-c", "echo read"], { slots: 1, lockDir: join(dir, "missing", "deeper"), timeoutMs: 30_000 });
|
|
61
|
+
expect(result.exitCode).toBe(0);
|
|
62
|
+
expect(result.stdout.text).toBe("read\n");
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { availableParallelism, tmpdir, totalmem } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { sleep } from "@intentic/base/async";
|
|
4
|
+
import { runBounded, type ProcessResult, type RunOptions } from "@intentic/base/process";
|
|
5
|
+
import { onPath } from "./tools.js";
|
|
6
|
+
|
|
7
|
+
// How many OCR readers run at once on this machine, across every process: each holds about 1.5 GiB of models and four
|
|
8
|
+
// threads, and fileq is started by many callers at once. ripgrep runs its preprocessor for twelve documents in
|
|
9
|
+
// parallel, so `rg` over a folder of unread scans started six readers (7 GiB) at once, and all six then ran past their
|
|
10
|
+
// time limit (measured 2026-11-23). The daemon's shadow keeper, its document routes and agents' own reads add more.
|
|
11
|
+
// The slots are flock(1) locks on files in /tmp, which every process here shares and the kernel releases however the
|
|
12
|
+
// holder ends. Without flock (macOS, a bare image) a run takes no slot, as before.
|
|
13
|
+
|
|
14
|
+
const CORES_PER_SLOT = 8;
|
|
15
|
+
const BYTES_PER_SLOT = 8 * 1024 ** 3;
|
|
16
|
+
const MAX_SLOTS = 2;
|
|
17
|
+
// flock's answer when the lock is held; the OCR command's own exits are 0, 1 and 2.
|
|
18
|
+
const BUSY = 75;
|
|
19
|
+
const POLL_FIRST_MS = 250;
|
|
20
|
+
const POLL_MAX_MS = 2_000;
|
|
21
|
+
|
|
22
|
+
/** One slot per eight cores and per 8 GiB, at least one and at most two. */
|
|
23
|
+
export const ocrSlotCount = (cores: number = availableParallelism(), memoryBytes: number = totalmem()): number =>
|
|
24
|
+
Math.max(1, Math.min(MAX_SLOTS, Math.floor(cores / CORES_PER_SLOT), Math.floor(memoryBytes / BYTES_PER_SLOT)));
|
|
25
|
+
|
|
26
|
+
export interface SlotOptions extends RunOptions {
|
|
27
|
+
readonly slots?: number;
|
|
28
|
+
/** Where the lock files live; /tmp unless a test says otherwise. */
|
|
29
|
+
readonly lockDir?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const lockDirOf = (options: SlotOptions): string => options.lockDir ?? (process.platform === "win32" ? tmpdir() : "/tmp");
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* `command args` run while holding one of the machine's OCR slots, waiting while every slot is held. `flock --no-fork`
|
|
36
|
+
* execs the command in its own place, so the command holds the lock itself and the time limit counts from the moment
|
|
37
|
+
* it has one. The command must not exit 64 or above: those are flock's own answers.
|
|
38
|
+
*/
|
|
39
|
+
export const runInOcrSlot = async (command: string, args: readonly string[], options: SlotOptions = {}): Promise<ProcessResult> => {
|
|
40
|
+
if (!onPath("flock")) {
|
|
41
|
+
return runBounded(command, args, options);
|
|
42
|
+
}
|
|
43
|
+
const slots = options.slots ?? ocrSlotCount();
|
|
44
|
+
const dir = lockDirOf(options);
|
|
45
|
+
for (let wait = POLL_FIRST_MS; ; wait = Math.min(wait * 2, POLL_MAX_MS)) {
|
|
46
|
+
for (let slot = 0; slot < slots; slot++) {
|
|
47
|
+
const lock = join(dir, `fileq-ocr-${String(slot)}.lock`);
|
|
48
|
+
const result = await runBounded("flock", ["--no-fork", "--nonblock", "--conflict-exit-code", String(BUSY), lock, command, ...args], options);
|
|
49
|
+
if (result.exitCode === BUSY) {
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
// A lock file flock could not open or lock (a read-only /tmp, another user's file) costs the slot, not the run.
|
|
53
|
+
if (result.exitCode !== null && result.exitCode >= 64 && result.stdout.text === "") {
|
|
54
|
+
return runBounded(command, args, options);
|
|
55
|
+
}
|
|
56
|
+
// An aborted run never starts, and comes back here as itself.
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
await sleep(wait, { signal: options.signal });
|
|
60
|
+
}
|
|
61
|
+
};
|
package/src/lib/sidecar.ts
CHANGED
|
@@ -207,7 +207,7 @@ export const writeSidecar = async (workspaceRoot: string, input: WriteSidecarInp
|
|
|
207
207
|
return written;
|
|
208
208
|
};
|
|
209
209
|
|
|
210
|
-
// The shadow tree ignores itself: outside the sandbox (fileq from npm
|
|
210
|
+
// The shadow tree ignores itself: outside the sandbox (fileq from npm) it lands inside somebody's
|
|
211
211
|
// repository, where a `git add -A` would sweep derived text of every document into a commit. `wx` leaves an existing
|
|
212
212
|
// file alone, so an owner's own edit to it wins; any other failure costs only the ignore, never the shadow.
|
|
213
213
|
export const ignoreShadowsInGit = async (workspaceRoot: string): Promise<void> => {
|
package/src/skill.ts
CHANGED
|
@@ -2,13 +2,13 @@ import { DERIVED_DIR } from "./lib/sidecar.js";
|
|
|
2
2
|
import { AUTHORING_RULES } from "./skill-authoring.js";
|
|
3
3
|
|
|
4
4
|
// fileq's own teaching: the SKILL.md every agent that has fileq on its PATH is given. It lives with the CLI it describes
|
|
5
|
-
// so a new flag and its sentence land together
|
|
6
|
-
//
|
|
5
|
+
// so a new flag and its sentence land together: the sandbox writes it into the workspace's skills (the daemon's
|
|
6
|
+
// settings/skills.ts), and a standalone install of fileq reads the same text.
|
|
7
7
|
// Only what the host itself provides differs: the sandbox image carries the `ocr` command (PaddleOCR, its models in the
|
|
8
8
|
// privacy image pack) and wires fileq as git's textconv; a standalone install has neither until its owner adds them.
|
|
9
9
|
|
|
10
10
|
export interface FileqSkillHost {
|
|
11
|
-
// "sandbox": the Intentic sandbox image. "standalone": fileq on anyone's machine (
|
|
11
|
+
// "sandbox": the Intentic sandbox image. "standalone": fileq on anyone's machine (npm).
|
|
12
12
|
readonly host: "sandbox" | "standalone";
|
|
13
13
|
}
|
|
14
14
|
|