@qvac/harness 1.0.0-rc.15 → 1.0.0-rc.16

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist-lib/index.d.ts +1 -0
  3. package/dist-lib/lib/capabilities/completion-engine/actors/execution-plan.js +2 -0
  4. package/dist-lib/lib/capabilities/completion-engine/engine.js +23 -39
  5. package/dist-lib/lib/contract/completion.d.ts +3 -0
  6. package/dist-lib/lib/contract/models.d.ts +1 -1
  7. package/dist-lib/lib/contract/ocr.d.ts +9 -0
  8. package/dist-lib/lib/contract/ocr.js +1 -0
  9. package/dist-lib/lib/models/gpu-selection.d.ts +6 -1
  10. package/dist-lib/lib/models/gpu-selection.js +29 -5
  11. package/dist-lib/lib/plugins/registry.d.ts +2 -0
  12. package/dist-lib/lib/serve.js +5 -34
  13. package/dist-lib/lib/spawn.d.ts +1 -0
  14. package/dist-lib/lib/tools/files/read-file.js +3 -3
  15. package/dist-lib/lib/tools/fs/document-text.d.ts +7 -1
  16. package/dist-lib/lib/tools/fs/document-text.js +9 -2
  17. package/dist-lib/lib/tools/operations/builders.d.ts +4 -3
  18. package/dist-lib/lib/tools/operations/builders.js +41 -3
  19. package/dist-lib/lib/tools/operations/calendar-range.d.ts +16 -0
  20. package/dist-lib/lib/tools/operations/calendar-range.js +40 -0
  21. package/dist-lib/lib/tools/operations/compile.js +4 -2
  22. package/dist-lib/lib/tools/operations/manifest.d.ts +4 -0
  23. package/dist-lib/lib/tools/pdf/build.d.ts +11 -1
  24. package/dist-lib/lib/tools/pdf/build.js +52 -16
  25. package/dist-lib/lib/tools/pdf/recognize.d.ts +13 -0
  26. package/dist-lib/lib/tools/pdf/recognize.js +58 -0
  27. package/dist-lib/lib/tools/pdf.js +18 -4
  28. package/dist-lib/plugins/ocr/bmp.d.ts +2 -0
  29. package/dist-lib/plugins/ocr/bmp.js +27 -0
  30. package/dist-lib/plugins/ocr/index.d.ts +12 -0
  31. package/dist-lib/plugins/ocr/index.js +18 -0
  32. package/dist-lib/plugins/ocr/ocr-runtime.d.ts +23 -0
  33. package/dist-lib/plugins/ocr/ocr-runtime.js +82 -0
  34. package/dist-lib/plugins/ocr/reading-order.d.ts +5 -0
  35. package/dist-lib/plugins/ocr/reading-order.js +71 -0
  36. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  37. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  38. package/package.json +10 -1
  39. package/scripts/addon-externals.cjs +3 -0
  40. package/worker/harness-sidecar.mjs +5 -0
  41. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +0 -20
  42. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +0 -110
  43. package/dist-lib/lib/helpers/input-budget.d.ts +0 -8
  44. package/dist-lib/lib/helpers/input-budget.js +0 -9
@@ -42,7 +42,7 @@ function operationTool(owningSkill, operation, transportTool) {
42
42
  },
43
43
  async execute(args, ctx) {
44
44
  const skillContext = { ...ctx, skills: [owningSkill] };
45
- const built = builder.build(args);
45
+ const built = builder.build(args, ctx);
46
46
  if ('error' in built) {
47
47
  return { error: `${operation.tool}: ${built.error}` };
48
48
  }
@@ -115,7 +115,9 @@ const PLACEHOLDER = /\{(\w+)\}/g;
115
115
  function fillTemplate(template, args, defaults) {
116
116
  const missing = [];
117
117
  const value = template.replace(PLACEHOLDER, (_match, name) => {
118
- const filled = args[name] ?? defaults?.[name];
118
+ const filled = args[name] === '' && defaults?.[name] !== undefined
119
+ ? defaults[name]
120
+ : (args[name] ?? defaults?.[name]);
119
121
  if (filled === undefined) {
120
122
  missing.push(name);
121
123
  }
@@ -17,6 +17,8 @@ declare const OperationSchema: z.ZodObject<{
17
17
  url: z.ZodString;
18
18
  builder: z.ZodEnum<{
19
19
  "calendar-add-meet": "calendar-add-meet";
20
+ "calendar-list-calendars": "calendar-list-calendars";
21
+ "calendar-list-events": "calendar-list-events";
20
22
  "calendar-meet-event": "calendar-meet-event";
21
23
  "docs-append-text": "docs-append-text";
22
24
  "docs-create": "docs-create";
@@ -45,6 +47,8 @@ declare const OperationSchema: z.ZodObject<{
45
47
  urlDefaults: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
46
48
  builder: z.ZodEnum<{
47
49
  "calendar-add-meet": "calendar-add-meet";
50
+ "calendar-list-calendars": "calendar-list-calendars";
51
+ "calendar-list-events": "calendar-list-events";
48
52
  "calendar-meet-event": "calendar-meet-event";
49
53
  "docs-append-text": "docs-append-text";
50
54
  "docs-create": "docs-create";
@@ -7,9 +7,14 @@ export interface Source {
7
7
  readonly fileName: string;
8
8
  readonly bytes: Uint8Array;
9
9
  }
10
+ export interface Recognized {
11
+ readonly pages: ReadonlyMap<number, string>;
12
+ readonly unreadFrom: number | null;
13
+ }
10
14
  export interface Opened {
11
15
  readonly source: Source;
12
16
  readonly doc: Doc;
17
+ readonly recognized?: Recognized | undefined;
13
18
  }
14
19
  export interface Built {
15
20
  readonly bytes: Uint8Array;
@@ -37,9 +42,14 @@ export interface ReadDocument {
37
42
  export interface ReadDocuments {
38
43
  readonly documents: readonly ReadDocument[];
39
44
  }
45
+ export interface ReadBudget {
46
+ chars: number;
47
+ }
48
+ export declare const READ_TEXT_LIMIT = 30000;
49
+ export declare function cleanText(text: string): string;
40
50
  export declare function pagesLabel(count: number): string;
41
51
  export type ShownPage = (fileName: string, page: number) => boolean;
42
- export declare function textless({ doc }: Opened): boolean;
52
+ export declare function textless(opened: Opened): boolean;
43
53
  export declare function everyPageShown({ source, doc }: Opened, isShown: ShownPage): boolean;
44
54
  export declare function shownNote({ source, doc }: Opened): string;
45
55
  export declare function readDocs(opened: readonly Opened[], isShown: ShownPage): ReadDocument | ReadDocuments;
@@ -1,5 +1,8 @@
1
1
  import b4a from 'b4a';
2
- const READ_TEXT_LIMIT = 30_000;
2
+ export const READ_TEXT_LIMIT = 30_000;
3
+ export function cleanText(text) {
4
+ return text.replace(/\r\n?/g, '\n').trim();
5
+ }
3
6
  function plural(count, noun) {
4
7
  return `${count} ${noun}${count === 1 ? '' : 's'}`;
5
8
  }
@@ -30,16 +33,39 @@ const SHOWN = {
30
33
  one: 'shown to you as an image in the user message, so read its content from that image',
31
34
  many: 'shown to you as images in the user message, so read their content from those images'
32
35
  };
33
- function scannedNote(scanned, shown) {
36
+ function scannedNote(scanned, { shown, blank }) {
34
37
  if (!scanned.length)
35
38
  return undefined;
36
39
  const one = scanned.length === 1;
37
40
  const what = one ? 'it is a scanned image' : 'they are scanned images';
38
- const where = shown ? SHOWN[one ? 'one' : 'many'] : 'and there is no OCR here';
41
+ let where = 'and there is no OCR here';
42
+ if (shown) {
43
+ where = SHOWN[one ? 'one' : 'many'];
44
+ }
45
+ else if (blank) {
46
+ where = `and OCR found no text on ${one ? 'it' : 'them'}`;
47
+ }
39
48
  return `${one ? 'page' : 'pages'} ${scanned.join(', ')} ${one ? 'has' : 'have'} no text layer: ${what}, ${where}`;
40
49
  }
41
- export function textless({ doc }) {
42
- for (const page of doc.textPages()) {
50
+ function recognizedNote(pages) {
51
+ if (!pages.length)
52
+ return undefined;
53
+ const one = pages.length === 1;
54
+ const what = one ? 'is a scanned image' : 'are scanned images';
55
+ return `${one ? 'page' : 'pages'} ${pages.join(', ')} ${what}, read here by OCR, so a word may be misread`;
56
+ }
57
+ function readNote(fileName, { read, scanned, blank }, isShown) {
58
+ const shown = scanned.every((page) => isShown(fileName, page));
59
+ const notes = [recognizedNote(read), scannedNote(scanned, { shown, blank })].filter((note) => note !== undefined);
60
+ return notes.length ? notes.join('; ') : undefined;
61
+ }
62
+ function* pageTexts({ doc, recognized }) {
63
+ for (const { page, text } of doc.textPages()) {
64
+ yield { page, text: recognized?.pages.get(page) ?? text };
65
+ }
66
+ }
67
+ export function textless(opened) {
68
+ for (const page of pageTexts(opened)) {
43
69
  if (page.text.trim())
44
70
  return false;
45
71
  }
@@ -57,29 +83,37 @@ export function shownNote({ source, doc }) {
57
83
  const what = one ? 'it is a scanned image' : 'its pages are scanned images';
58
84
  return `${source.fileName} has no text layer: ${what}, ${SHOWN[one ? 'one' : 'many']}`;
59
85
  }
60
- function readOne({ source, doc }, budget, isShown) {
86
+ function readOne(opened, budget, isShown) {
87
+ const { source, doc, recognized } = opened;
88
+ const unreadFrom = recognized?.unreadFrom ?? Infinity;
61
89
  const pages = [];
90
+ const read = [];
62
91
  const scanned = [];
63
92
  let truncated = false;
64
- for (const { page, text } of doc.textPages()) {
65
- const clean = text.replace(/\r\n?/g, '\n').trim();
66
- if (!clean) {
93
+ for (const { page, text } of pageTexts(opened)) {
94
+ const unread = page >= unreadFrom;
95
+ const clean = cleanText(text);
96
+ if (!clean && !unread) {
67
97
  scanned.push(page + 1);
68
98
  }
69
99
  const kept = clean.slice(0, Math.max(0, budget.chars));
70
100
  budget.chars -= kept.length;
71
- truncated ||= kept.length < clean.length;
101
+ truncated ||= unread || kept.length < clean.length;
72
102
  if (budget.chars > 0 || kept) {
73
103
  pages.push({ page: page + 1, text: kept });
104
+ if (kept && recognized?.pages.has(page)) {
105
+ read.push(page + 1);
106
+ }
74
107
  }
75
108
  }
109
+ const blank = scanned.every((page) => recognized?.pages.has(page - 1));
76
110
  return {
77
111
  attachmentId: source.attachmentId,
78
112
  fileName: source.fileName,
79
113
  pageCount: doc.pageCount(),
80
114
  pages,
81
115
  fields: doc.fields().map(describeField),
82
- note: scannedNote(scanned, scanned.every((page) => isShown(source.fileName, page))),
116
+ note: readNote(source.fileName, { read, scanned, blank }, isShown),
83
117
  truncated: truncated || undefined
84
118
  };
85
119
  }
@@ -104,12 +138,14 @@ function joinPages(pdfium, parts, pages) {
104
138
  out.close();
105
139
  }
106
140
  }
107
- function textFile({ source, doc }) {
108
- const text = [...doc.textPages()]
109
- .map((page) => page.text.replace(/\r\n?/g, '\n').trim())
110
- .join('\n\n');
141
+ function textFile(opened) {
142
+ const { source, doc } = opened;
143
+ const text = [...pageTexts(opened)].map((page) => cleanText(page.text)).join('\n\n');
111
144
  if (!text.trim()) {
112
- return `${source.fileName} has no text layer: its pages are scanned images, and there is no OCR here`;
145
+ const why = opened.recognized?.pages.size
146
+ ? 'and OCR found no text on them'
147
+ : 'and there is no OCR here';
148
+ return `${source.fileName} has no text layer: its pages are scanned images, ${why}`;
113
149
  }
114
150
  return { bytes: b4a.from(text + '\n', 'utf8'), pageCount: doc.pageCount() };
115
151
  }
@@ -0,0 +1,13 @@
1
+ import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
+ import type { OcrService } from '../../contract/ocr.ts';
3
+ import { type Doc, type ReadBudget, type Recognized } from './build.ts';
4
+ export interface ScannedDocument {
5
+ readonly doc: Doc;
6
+ readonly bytes: Uint8Array;
7
+ }
8
+ export interface RecognizeOptions {
9
+ readonly ocr: OcrService;
10
+ readonly signal?: BareAbortSignal | undefined;
11
+ readonly budget?: ReadBudget | undefined;
12
+ }
13
+ export declare function recognizePages({ doc, bytes }: ScannedDocument, { ocr, signal, budget }: RecognizeOptions): Promise<Recognized>;
@@ -0,0 +1,58 @@
1
+ import { createHash } from 'crypto';
2
+ import { errorMessage } from '../../guards.js';
3
+ import { HarnessLog } from '../../log.js';
4
+ import { cleanText } from './build.js';
5
+ const OCR_SCALE = 2;
6
+ const KEPT_DOCUMENTS = 8;
7
+ const keptByService = new WeakMap();
8
+ export async function recognizePages({ doc, bytes }, { ocr, signal, budget }) {
9
+ const pages = new Map();
10
+ let kept = null;
11
+ let failed = false;
12
+ for (const { page, text } of doc.textPages()) {
13
+ if (budget && budget.chars <= 0) {
14
+ return { pages, unreadFrom: page };
15
+ }
16
+ let read = cleanText(text);
17
+ if (!read && !failed && doc.pageFlags(page).hasImage) {
18
+ kept ??= keptPages(ocr, bytes);
19
+ const found = kept.get(page) ?? (await readPage(doc, page, { ocr, signal }));
20
+ failed = found === null;
21
+ if (found !== null) {
22
+ kept.set(page, found);
23
+ pages.set(page, found);
24
+ read = found;
25
+ }
26
+ }
27
+ if (budget) {
28
+ budget.chars -= read.length;
29
+ }
30
+ }
31
+ return { pages, unreadFrom: null };
32
+ }
33
+ async function readPage(doc, page, { ocr, signal }) {
34
+ try {
35
+ return cleanText(await ocr.read(await doc.renderAsync(page, { scale: OCR_SCALE }), signal));
36
+ }
37
+ catch (err) {
38
+ if (signal?.aborted) {
39
+ throw err;
40
+ }
41
+ HarnessLog.warn('ocr failed; scanned pages stay unread', { page, err: errorMessage(err) });
42
+ return null;
43
+ }
44
+ }
45
+ function keptPages(ocr, bytes) {
46
+ const documents = keptByService.get(ocr) ?? new Map();
47
+ keptByService.set(ocr, documents);
48
+ const id = createHash('sha256').update(bytes).digest('hex');
49
+ const pages = documents.get(id) ?? new Map();
50
+ documents.delete(id);
51
+ documents.set(id, pages);
52
+ for (const oldest of documents.keys()) {
53
+ if (documents.size <= KEPT_DOCUMENTS)
54
+ break;
55
+ documents.delete(oldest);
56
+ }
57
+ return pages;
58
+ }
@@ -1,7 +1,8 @@
1
1
  import { errorCode, errorMessage } from '../guards.js';
2
2
  import { checkOutputBytes, RUN_OUTPUT_BUDGET_BYTES } from './attachments/output-policy.js';
3
- import { build, pagesLabel, everyPageShown, readDocs, shownNote, textless } from './pdf/build.js';
3
+ import { build, pagesLabel, everyPageShown, readDocs, READ_TEXT_LIMIT, shownNote, textless } from './pdf/build.js';
4
4
  import { placeImages } from './pdf/images.js';
5
+ import { recognizePages } from './pdf/recognize.js';
5
6
  import { PAGE_SIZES, parseRequest, PDF_ACTIONS, WHERE_IDS_ARE } from './pdf/request.js';
6
7
  export { parsePages, parseRequest } from './pdf/request.js';
7
8
  const SUFFIXES = {
@@ -208,6 +209,18 @@ function shownPages(ctx) {
208
209
  const names = (ctx.turnImages ?? []).map((image) => image.path.split(/[\\/]/).pop()?.slice(33));
209
210
  return (fileName, page) => names.includes(renderedPageName(fileName, page));
210
211
  }
212
+ async function withRecognized(opened, request, { ocr, signal }) {
213
+ if (!ocr || (request.action !== 'read' && request.action !== 'text')) {
214
+ return opened;
215
+ }
216
+ const budget = request.action === 'read' ? { chars: READ_TEXT_LIMIT } : undefined;
217
+ const out = [];
218
+ for (const one of opened) {
219
+ const scanned = { doc: one.doc, bytes: one.source.bytes };
220
+ out.push({ ...one, recognized: await recognizePages(scanned, { ocr, signal, budget }) });
221
+ }
222
+ return out;
223
+ }
211
224
  async function run(pdfium, asked, ctx) {
212
225
  if (asked.action === 'create') {
213
226
  const placed = await placeImages(asked, ctx);
@@ -223,17 +236,18 @@ async function run(pdfium, asked, ctx) {
223
236
  if (error) {
224
237
  return { error };
225
238
  }
239
+ const read = await withRecognized(opened, request, ctx);
226
240
  if (request.action === 'read') {
227
- return readDocs(opened, shownPages(ctx));
241
+ return readDocs(read, shownPages(ctx));
228
242
  }
229
- const [only] = opened;
243
+ const [only] = read;
230
244
  if (request.action === 'text' &&
231
245
  only &&
232
246
  textless(only) &&
233
247
  everyPageShown(only, shownPages(ctx))) {
234
248
  return { note: shownNote(only) };
235
249
  }
236
- return await deliver({ pdfium, request, opened }, ctx);
250
+ return await deliver({ pdfium, request, opened: read }, ctx);
237
251
  }
238
252
  finally {
239
253
  for (const { doc } of opened) {
@@ -0,0 +1,2 @@
1
+ import type { OcrImage } from '../../lib/contract/ocr.ts';
2
+ export declare function bmp({ width, height, data }: OcrImage): Uint8Array;
@@ -0,0 +1,27 @@
1
+ import b4a from 'b4a';
2
+ const HEADER_BYTES = 54;
3
+ export function bmp({ width, height, data }) {
4
+ const row = (width * 3 + 3) & ~3;
5
+ const bytes = b4a.alloc(HEADER_BYTES + row * height);
6
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
7
+ bytes[0] = 0x42;
8
+ bytes[1] = 0x4d;
9
+ view.setUint32(2, bytes.byteLength, true);
10
+ view.setUint32(10, HEADER_BYTES, true);
11
+ view.setUint32(14, 40, true);
12
+ view.setInt32(18, width, true);
13
+ view.setInt32(22, height, true);
14
+ view.setUint16(26, 1, true);
15
+ view.setUint16(28, 24, true);
16
+ view.setUint32(34, row * height, true);
17
+ for (let y = 0; y < height; y++) {
18
+ const from = (height - 1 - y) * width * 4;
19
+ const to = HEADER_BYTES + y * row;
20
+ for (let x = 0; x < width; x++) {
21
+ bytes[to + x * 3] = data[from + x * 4 + 2] ?? 0;
22
+ bytes[to + x * 3 + 1] = data[from + x * 4 + 1] ?? 0;
23
+ bytes[to + x * 3 + 2] = data[from + x * 4] ?? 0;
24
+ }
25
+ }
26
+ return bytes;
27
+ }
@@ -0,0 +1,12 @@
1
+ import type { HarnessPlugin, PluginContext, PluginSetup } from '../../lib/plugins/index.ts';
2
+ export declare class Ocr implements HarnessPlugin {
3
+ readonly name = "ocr";
4
+ readonly api = 1;
5
+ readonly provides: string[];
6
+ readonly needs: string[];
7
+ readonly addons: {
8
+ 'ocr-ggml': () => Promise<typeof import("@qvac/ocr-ggml/addonLogging")>;
9
+ };
10
+ constructor();
11
+ setup(ctx: PluginContext): PluginSetup;
12
+ }
@@ -0,0 +1,18 @@
1
+ import { PluginRegistry } from '../../lib/plugins/index.js';
2
+ import { OcrRuntime } from './ocr-runtime.js';
3
+ export class Ocr {
4
+ name = 'ocr';
5
+ api = PluginRegistry.API_VERSION;
6
+ provides = ['ocr'];
7
+ needs = ['models'];
8
+ addons = { 'ocr-ggml': () => import('@qvac/ocr-ggml/addonLogging') };
9
+ constructor() {
10
+ PluginRegistry.requirePeers('ocr', {
11
+ '@qvac/ocr-ggml': () => import.meta.resolve('@qvac/ocr-ggml/addonLogging')
12
+ });
13
+ }
14
+ setup(ctx) {
15
+ const runtime = new OcrRuntime(ctx.service('models'));
16
+ return { services: { ocr: runtime }, unloadIdle: () => runtime.unloadIdle() };
17
+ }
18
+ }
@@ -0,0 +1,23 @@
1
+ import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
+ import type { ModelHost } from '../../lib/contract/models.ts';
3
+ import type { OcrImage, OcrService } from '../../lib/contract/ocr.ts';
4
+ import { type OcrBlock } from './reading-order.ts';
5
+ export interface OcrSdk {
6
+ ocr(params: {
7
+ modelId: string;
8
+ image: Uint8Array;
9
+ }): {
10
+ blocks: Promise<OcrBlock[]>;
11
+ };
12
+ }
13
+ export declare class OcrRuntime implements OcrService {
14
+ private readonly _models;
15
+ private readonly _loadSdk;
16
+ private readonly _pool;
17
+ private _tail;
18
+ constructor(models: ModelHost);
19
+ read(image: OcrImage, signal?: BareAbortSignal): Promise<string>;
20
+ unloadIdle(): Promise<void>;
21
+ private _open;
22
+ private _serial;
23
+ }
@@ -0,0 +1,82 @@
1
+ import { OCR_DOCTR, OCR_DOCTR_1 } from '@qvac/inference/models';
2
+ import { errorMessage } from '../../lib/guards.js';
3
+ import { raceAbort } from '../../lib/helpers/race-abort.js';
4
+ import { retryMemo } from '../../lib/helpers/retry-memo.js';
5
+ import { HarnessLog } from '../../lib/log.js';
6
+ import { bmp } from './bmp.js';
7
+ import { readingOrder } from './reading-order.js';
8
+ const OCR_MODEL_LABEL = 'OCR model';
9
+ function ocrSdk(models) {
10
+ return retryMemo(async () => {
11
+ const sdk = await models.sdk();
12
+ if (typeof globalThis.Bare !== 'undefined') {
13
+ const [{ ocrPlugin }, { registerPlugin }] = await Promise.all([
14
+ import('@qvac/inference/ggml-ocr/plugin'),
15
+ import('@qvac/inference/plugin-registry')
16
+ ]);
17
+ try {
18
+ registerPlugin(ocrPlugin);
19
+ }
20
+ catch (err) {
21
+ HarnessLog.warn('plugin registration skipped', { plugin: 'ocr', err: errorMessage(err) });
22
+ }
23
+ }
24
+ return sdk;
25
+ });
26
+ }
27
+ export class OcrRuntime {
28
+ _models;
29
+ _loadSdk;
30
+ _pool;
31
+ _tail = Promise.resolve();
32
+ constructor(models) {
33
+ this._models = models;
34
+ this._loadSdk = ocrSdk(models);
35
+ this._pool = models.registerPool({
36
+ addon: 'ocr',
37
+ modelType: 'ggml-ocr',
38
+ modelConfig: { pipelineType: 'doctr', detectorModelSrc: OCR_DOCTR_1 },
39
+ label: OCR_MODEL_LABEL,
40
+ sdk: this._loadSdk
41
+ });
42
+ }
43
+ async read(image, signal) {
44
+ const { held, releaseWork } = this._open();
45
+ let job = null;
46
+ try {
47
+ const { modelId } = await raceAbort(held.load(), signal);
48
+ const sdk = await this._loadSdk();
49
+ job = this._serial(async () => readingOrder(await sdk.ocr({ modelId, image: bmp(image) }).blocks));
50
+ return await raceAbort(job, signal);
51
+ }
52
+ finally {
53
+ void Promise.allSettled([job ?? held.peek()]).then(() => {
54
+ try {
55
+ held.release();
56
+ }
57
+ finally {
58
+ releaseWork();
59
+ }
60
+ });
61
+ }
62
+ }
63
+ unloadIdle() {
64
+ return this._pool.evictIdle(() => true);
65
+ }
66
+ _open() {
67
+ const releaseWork = this._models.enterWork();
68
+ try {
69
+ return { held: this._pool.open(OCR_DOCTR.src), releaseWork };
70
+ }
71
+ catch (error) {
72
+ releaseWork();
73
+ throw error;
74
+ }
75
+ }
76
+ _serial(job) {
77
+ const run = this._tail.then(job);
78
+ this._tail = run.catch(noop);
79
+ return run;
80
+ }
81
+ }
82
+ function noop() { }
@@ -0,0 +1,5 @@
1
+ export interface OcrBlock {
2
+ readonly text: string;
3
+ readonly bbox?: readonly [number, number, number, number] | undefined;
4
+ }
5
+ export declare function readingOrder(blocks: readonly OcrBlock[]): string;
@@ -0,0 +1,71 @@
1
+ const COLUMNS = { start: 'left', end: 'right' };
2
+ const ROWS = { start: 'top', end: 'bottom' };
3
+ const COLUMN_GAP = 1.5;
4
+ const BLOCK_GAP = 1;
5
+ const COLUMN_WORDS = 4;
6
+ export function readingOrder(blocks) {
7
+ const words = blocks.flatMap(({ text, bbox }) => bbox ? [{ text, left: bbox[0], top: bbox[1], right: bbox[2], bottom: bbox[3] }] : []);
8
+ if (words.length < blocks.length) {
9
+ return blocks.map((block) => block.text).join('\n');
10
+ }
11
+ return regionLines(words, medianHeight(words)).join('\n');
12
+ }
13
+ function regionLines(words, lineHeight) {
14
+ const columns = split(words, COLUMNS, lineHeight * COLUMN_GAP);
15
+ if (columns?.every((column) => column.length / chainLines(column).length >= COLUMN_WORDS)) {
16
+ return columns.flatMap((column) => regionLines(column, lineHeight));
17
+ }
18
+ const blocks = split(words, ROWS, lineHeight * BLOCK_GAP);
19
+ if (blocks) {
20
+ return blocks.flatMap((block) => regionLines(block, lineHeight));
21
+ }
22
+ return chainLines(words).map((line) => line.words.map((word) => word.text).join(' '));
23
+ }
24
+ function split(words, { start, end }, gap) {
25
+ const parts = [];
26
+ let reach = -Infinity;
27
+ for (const word of [...words].sort((a, b) => a[start] - b[start])) {
28
+ if (word[start] - reach >= gap) {
29
+ parts.push([]);
30
+ }
31
+ parts.at(-1)?.push(word);
32
+ reach = Math.max(reach, word[end]);
33
+ }
34
+ return parts.length > 1 ? parts : null;
35
+ }
36
+ function chainLines(words) {
37
+ const lines = [];
38
+ for (const word of [...words].sort((a, b) => a.left - b.left)) {
39
+ const line = levelWith(lines, word);
40
+ if (line) {
41
+ line.words.push(word);
42
+ line.last = word;
43
+ }
44
+ else {
45
+ lines.push({ first: word, last: word, words: [word] });
46
+ }
47
+ }
48
+ return lines.sort((a, b) => middle(a.first) - middle(b.first));
49
+ }
50
+ function levelWith(lines, word) {
51
+ let closest;
52
+ let offset = Infinity;
53
+ for (const line of lines) {
54
+ const apart = Math.abs(middle(line.last) - middle(word));
55
+ if (apart < height(line.last) / 2 && apart < offset) {
56
+ closest = line;
57
+ offset = apart;
58
+ }
59
+ }
60
+ return closest;
61
+ }
62
+ function middle(word) {
63
+ return (word.top + word.bottom) / 2;
64
+ }
65
+ function height(word) {
66
+ return word.bottom - word.top;
67
+ }
68
+ function medianHeight(words) {
69
+ const heights = words.map(height).sort((a, b) => a - b);
70
+ return heights[Math.floor(heights.length / 2)] ?? 0;
71
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qvac/harness",
3
- "version": "1.0.0-rc.15",
3
+ "version": "1.0.0-rc.16",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "bare": ">=1.34.0",
@@ -364,6 +364,10 @@
364
364
  "types": "./dist-lib/plugins/obsidian/index.d.ts",
365
365
  "default": "./dist-lib/plugins/obsidian/index.js"
366
366
  },
367
+ "./plugins/ocr": {
368
+ "types": "./dist-lib/plugins/ocr/index.d.ts",
369
+ "default": "./dist-lib/plugins/ocr/index.js"
370
+ },
367
371
  "./plugins/quickjs": {
368
372
  "types": "./dist-lib/plugins/quickjs/index.d.ts",
369
373
  "default": "./dist-lib/plugins/quickjs/index.js"
@@ -635,6 +639,7 @@
635
639
  "@qvac/embed-llamacpp": "^0.53.0",
636
640
  "@qvac/langdetect-text": "^0.1.2",
637
641
  "@qvac/llm-llamacpp": "^0.65.0",
642
+ "@qvac/ocr-ggml": "^0.31.0",
638
643
  "@qvac/sdk": "^0.23.0",
639
644
  "@qvac/translation-nmtcpp": "^0.23.0",
640
645
  "@qvac/tts-ggml": "^0.14.0",
@@ -675,6 +680,9 @@
675
680
  "@qvac/llm-llamacpp": {
676
681
  "optional": true
677
682
  },
683
+ "@qvac/ocr-ggml": {
684
+ "optional": true
685
+ },
678
686
  "@qvac/sdk": {
679
687
  "optional": true
680
688
  },
@@ -727,6 +735,7 @@
727
735
  "@qvac/embed-llamacpp": "^0.53.0",
728
736
  "@qvac/langdetect-text": "^0.1.2",
729
737
  "@qvac/llm-llamacpp": "^0.65.0",
738
+ "@qvac/ocr-ggml": "^0.31.0",
730
739
  "@qvac/sdk": "^0.23.0",
731
740
  "@qvac/translation-nmtcpp": "^0.23.0",
732
741
  "@qvac/tts-ggml": "^0.14.0",
@@ -27,6 +27,7 @@ const NATIVE_ADDON_PACKAGES = [
27
27
  '@qvac/embed-llamacpp',
28
28
  '@qvac/fabric',
29
29
  '@qvac/llm-llamacpp',
30
+ '@qvac/ocr-ggml',
30
31
  '@qvac/translation-nmtcpp',
31
32
  '@qvac/tts-ggml',
32
33
  '@qvac/turbovec-ggml',
@@ -48,6 +49,8 @@ const NATIVE_ADDON_PACKAGES = [
48
49
  'bare-ico',
49
50
  'bare-image-resample',
50
51
  'bare-inspect',
52
+ // @qvac/ocr-ggml ships brittle as a runtime dependency, and brittle's bare-cov needs this
53
+ 'bare-inspector',
51
54
  'bare-jpeg',
52
55
  'bare-logger',
53
56
  'bare-module',
@@ -6,6 +6,7 @@ import { Knowledge } from '../dist-lib/plugins/knowledge/index.js'
6
6
  import { McpPlugin } from '../dist-lib/plugins/mcp/index.js'
7
7
  import { Music } from '../dist-lib/plugins/music/index.js'
8
8
  import { ObsidianRoute } from '../dist-lib/plugins/obsidian/index.js'
9
+ import { Ocr } from '../dist-lib/plugins/ocr/index.js'
9
10
  import { Python } from '../dist-lib/plugins/python/index.js'
10
11
  import { Speech } from '../dist-lib/plugins/speech/index.js'
11
12
  import { TranslationPlugin } from '../dist-lib/plugins/translation/index.js'
@@ -38,6 +39,10 @@ export function firstPartyPlugins({
38
39
  read: ['mcp_call']
39
40
  })
40
41
  ]
42
+ if (pluginOptions.ocr !== false) {
43
+ plugins.push(new Ocr())
44
+ }
45
+
41
46
  if (imageModel) {
42
47
  // granted read so a generation does not ask for approval; edit_image stays a write
43
48
  plugins.push(new Image({ model: imageModel, clamps: imageClamps, read: ['generate_image'] }))