ppu-indra-ocr 0.0.0-stage → 0.1.2

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 (95) hide show
  1. package/LICENSE +202 -0
  2. package/LICENSE-STATUS.md +112 -0
  3. package/NOTICE +20 -0
  4. package/README.md +830 -2
  5. package/cli/commands.d.ts +9 -0
  6. package/cli/commands.js +11 -0
  7. package/cli/help.d.ts +5 -0
  8. package/cli/help.js +50 -0
  9. package/cli/index.d.ts +2 -0
  10. package/cli/index.js +6 -0
  11. package/cli/io.d.ts +27 -0
  12. package/cli/io.js +6 -0
  13. package/cli/options.d.ts +19 -0
  14. package/cli/options.js +1 -0
  15. package/cli/run.d.ts +1 -0
  16. package/cli/run.js +9 -0
  17. package/coi-serviceworker.js +130 -0
  18. package/core/batch.d.ts +53 -0
  19. package/core/batch.js +1 -0
  20. package/core/indra-ocr.service.d.ts +65 -0
  21. package/core/indra-ocr.service.js +1 -0
  22. package/core/one-shot.d.ts +5 -0
  23. package/core/one-shot.js +1 -0
  24. package/core/opencv-image-ops.d.ts +10 -0
  25. package/core/opencv-image-ops.js +1 -0
  26. package/core/platform.d.ts +40 -0
  27. package/core/session-factory.d.ts +23 -0
  28. package/core/session-factory.js +1 -0
  29. package/exports.d.ts +15 -0
  30. package/exports.js +1 -0
  31. package/index.d.ts +11 -0
  32. package/index.js +1 -0
  33. package/indra/assemble.d.ts +22 -0
  34. package/indra/assemble.js +3 -0
  35. package/indra/det-post.d.ts +34 -0
  36. package/indra/det-post.js +1 -0
  37. package/indra/document.d.ts +36 -0
  38. package/indra/document.js +1 -0
  39. package/indra/image.d.ts +43 -0
  40. package/indra/image.js +1 -0
  41. package/indra/layout-post.d.ts +35 -0
  42. package/indra/layout-post.js +9 -0
  43. package/indra/lines.d.ts +19 -0
  44. package/indra/lines.js +1 -0
  45. package/indra/math.d.ts +54 -0
  46. package/indra/math.js +1 -0
  47. package/indra/numeric.d.ts +9 -0
  48. package/indra/numeric.js +1 -0
  49. package/indra/order-post.d.ts +37 -0
  50. package/indra/order-post.js +1 -0
  51. package/indra/pipeline.d.ts +65 -0
  52. package/indra/pipeline.js +1 -0
  53. package/indra/rec-preproc.d.ts +28 -0
  54. package/indra/rec-preproc.js +1 -0
  55. package/indra/recognize.d.ts +29 -0
  56. package/indra/recognize.js +1 -0
  57. package/indra/textlayer.d.ts +72 -0
  58. package/indra/textlayer.js +2 -0
  59. package/indra/ts-image-ops.d.ts +3 -0
  60. package/indra/ts-image-ops.js +1 -0
  61. package/indra/types.d.ts +101 -0
  62. package/indra/upright.d.ts +28 -0
  63. package/indra/upright.js +1 -0
  64. package/indra/util.d.ts +14 -0
  65. package/indra/util.js +1 -0
  66. package/indra/vocab.d.ts +14 -0
  67. package/indra/vocab.js +1 -0
  68. package/interface.d.ts +61 -0
  69. package/mobile/index.d.ts +26 -0
  70. package/mobile/index.js +1 -0
  71. package/mobile/indra-ocr.service.mobile.d.ts +11 -0
  72. package/mobile/indra-ocr.service.mobile.js +1 -0
  73. package/mobile/platform.mobile.d.ts +16 -0
  74. package/mobile/platform.mobile.js +1 -0
  75. package/model-catalogue.d.ts +38 -0
  76. package/model-catalogue.js +1 -0
  77. package/package.json +109 -4
  78. package/pdf/index.d.ts +31 -0
  79. package/pdf/index.js +1 -0
  80. package/pdf/pdfium.d.ts +27 -0
  81. package/pdf/pdfium.js +1 -0
  82. package/processor/indra-ocr.service.d.ts +28 -0
  83. package/processor/indra-ocr.service.js +1 -0
  84. package/processor/model-cache.d.ts +17 -0
  85. package/processor/model-cache.js +2 -0
  86. package/processor/platform.node.d.ts +13 -0
  87. package/processor/platform.node.js +1 -0
  88. package/utils.d.ts +36 -0
  89. package/utils.js +2 -0
  90. package/web/index.d.ts +26 -0
  91. package/web/index.js +1 -0
  92. package/web/indra-ocr.service.web.d.ts +15 -0
  93. package/web/indra-ocr.service.web.js +1 -0
  94. package/web/platform.web.d.ts +32 -0
  95. package/web/platform.web.js +1 -0
@@ -0,0 +1,9 @@
1
+ import type { Page } from "../indra/types.js";
2
+ import type { CliValues, OutputFormat } from "./options.js";
3
+ /** Pages in the chosen format: markdown, plain text, or one JSON object per page. */
4
+ export declare function renderPages(pages: readonly Page[], fmt: OutputFormat, pretty: boolean): string;
5
+ export declare function runConvert(patterns: string[], values: CliValues): Promise<void>;
6
+ export declare function runDetect(images: string[], values: CliValues): Promise<void>;
7
+ export declare function runDownloadModels(values: CliValues): Promise<void>;
8
+ export declare function runClearCache(values: CliValues): void;
9
+ export declare function runModels(values: CliValues): void;
@@ -0,0 +1,11 @@
1
+ import{mkdirSync,rmSync}from"node:fs";import{basename,extname,join}from"node:path";import{isPdf}from"../indra/document.js";import{BASE_FILES,MATH_FILES,MODEL_FILES,MODEL_REVISION,defaultModelUrl}from"../model-catalogue.js";import{CACHE_DIR}from"../processor/model-cache.js";import{IndraOcrService}from"../processor/indra-ocr.service.js";import{CliError,expandPatterns,isMissingLocalFile,loadImageInput,logStderr,writeOutput}from"./io.js";import{buildIndraOptions,buildPdfOptions,format,str}from"./options.js";let EXTENSIONS={md:".md",text:".txt",json:".jsonl"};function errMessage(reason){return reason instanceof Error?reason.message:String(reason)}export function renderPages(pages,fmt,pretty){if(fmt==="text")return pages.map((p)=>p.text).join(`
2
+ `);if(fmt==="json")return pages.map((p,page)=>JSON.stringify({page,...p},null,pretty?2:undefined)).join(`
3
+ `);return pages.map((p)=>p.markdown??p.text).join(`
4
+
5
+ `)}async function readPdf(service,bytes,values){let pdf;try{pdf=await import("../pdf/index.js")}catch(err){throw new CliError(`PDF input needs the optional '@embedpdf/pdfium' package: npm install @embedpdf/pdfium (${errMessage(err)})`)}return pdf.convertPdf(service,bytes,buildPdfOptions(values))}async function withService(values,run){let service=new IndraOcrService(buildIndraOptions(values));try{logStderr("Loading models...",Boolean(values.quiet));await service.initialize();return await run(service)}finally{await service.destroy()}}export async function runConvert(patterns,values){if(!patterns.length)throw new CliError("convert takes one or more files",2);let files=expandPatterns(patterns);let missing=files.filter(isMissingLocalFile);if(missing.length)throw new CliError(`No such file${missing.length>1?"s":""}: ${missing.join(", ")}`);let fmt=format(values);let outDir=str(values,"out");if(outDir)mkdirSync(outDir,{recursive:true});let outputs=[];let failed=0;await withService(values,async(service)=>{for(let file of files){try{let bytes=await loadImageInput(file);let pages=isPdf(bytes)?await readPdf(service,bytes,values):[await service.convert(bytes)];if(values.timings){for(const[i,p]of pages.entries()){process.stderr.write(`${file} p${i+1}: ${p.source} ${Math.round(p.timings["total_ms"]??0)} ms (${p.note})
6
+ `)}}let rendered=renderPages(pages,fmt,Boolean(values.pretty));if(outDir){writeOutput(rendered,join(outDir,basename(file,extname(file))+EXTENSIONS[fmt]))}else{outputs.push(rendered)}}catch(err){failed++;process.stderr.write(`${file}: ${errMessage(err)}
7
+ `)}}});if(!outDir&&outputs.length)writeOutput(outputs.join(fmt==="md"?`
8
+
9
+ `:`
10
+ `),str(values,"output"));if(failed)throw new CliError(`${failed} of ${files.length} file(s) failed`)}export async function runDetect(images,values){const[image]=images;if(!image||images.length!==1)throw new CliError("detect takes exactly one image",2);if(isMissingLocalFile(image))throw new CliError(`No such file: ${image}`);let boxes=await withService(values,async(service)=>service.detect(await loadImageInput(image)));let out=boxes.map(([x0,y0,x1,y1,score])=>({box:[x0,y0,x1,y1],score}));writeOutput(JSON.stringify(out,null,values.pretty?2:undefined),str(values,"output"))}export async function runDownloadModels(values){await withService(values,async()=>{return});logStderr(`Models cached in ${CACHE_DIR}`,Boolean(values.quiet))}export function runClearCache(values){rmSync(CACHE_DIR,{recursive:true,force:true});logStderr(`Removed ${CACHE_DIR}`,Boolean(values.quiet))}export function runModels(values){let roles=[...BASE_FILES,...MATH_FILES];let models=roles.map((role)=>({role,file:MODEL_FILES[role],url:defaultModelUrl(role),math:MATH_FILES.includes(role)}));if(format(values)==="json"){writeOutput(JSON.stringify({revision:MODEL_REVISION,cache:CACHE_DIR,models},null,values.pretty?2:undefined));return}let lines=models.map((m)=>` ${m.file.padEnd(20)}${m.math?" (--math)":""}`);writeOutput([`Indra OCR models, revision ${MODEL_REVISION} (datalab-to/indra-ocr)`,`Cache: ${CACHE_DIR}`,...lines,"","Weights: Datalab, modified OpenRAIL-M license with use restrictions."].join(`
11
+ `),str(values,"output"))}
package/cli/help.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Usage text for the `ppu-indra-ocr` CLI. Printed to stdout for `help` /
3
+ * `--help`, and to stderr (followed by a non-zero exit) on usage errors.
4
+ */
5
+ export declare const USAGE = "ppu-indra-ocr - Indra OCR on the command line\n\nUsage:\n ppu-indra-ocr <command> [args] [flags]\n\nCommands:\n convert <file...> OCR images and PDFs (paths, globs, or http(s) URLs)\n detect <image> Detect text lines only (JSON boxes to stdout)\n download-models Pre-warm the model cache (~/.cache/ppu-indra-ocr)\n clear-cache Delete the cached model files\n models Print the model files, their URLs and the revision\n help Show this help\n version Show the installed version\n\nConvert flags:\n --format <f> md | text | json (default md; json is one object per page)\n --out <dir> write one file per input (.md, .txt or .jsonl)\n --math write math as LaTeX (loads 4 more models)\n --keep-furniture keep page headers and footers in the markdown\n --engine <e> opencv | canvas-native (default opencv)\n --timings print per-page source and time to stderr\n\nPDF flags:\n --mode <m> auto | ocr | text (default auto: text layer where sound, OCR elsewhere)\n --dpi <n> render resolution for OCR (default 200)\n --max-pages <n> read at most n pages per PDF\n --password <p> password for encrypted PDFs\n --model-order order text-layer lines with the order model, not the PDF content order\n --no-image-ocr on text-layer pages, do not OCR text inside images\n\nModels and session:\n --model-dir <dir> read the model files from a folder instead of downloading\n --execution-providers <list> comma-separated, e.g. cpu or cuda,cpu (default cpu)\n\nOutput:\n -o, --output <file> write everything to one file instead of stdout\n --pretty indent JSON output\n -q, --quiet suppress progress on stderr\n --verbose log each step to stderr\n\nExamples:\n ppu-indra-ocr convert paper.pdf\n ppu-indra-ocr convert \"scans/*.png\" --out results/\n ppu-indra-ocr convert scan.png --format json --pretty\n ppu-indra-ocr convert paper.pdf --mode ocr --math --timings\n ppu-indra-ocr detect receipt.jpg\n\nThe model weights are Datalab's (https://huggingface.co/datalab-to/indra-ocr),\nunder a modified OpenRAIL-M license with use restrictions.\n";
package/cli/help.js ADDED
@@ -0,0 +1,50 @@
1
+ export let USAGE=`ppu-indra-ocr - Indra OCR on the command line
2
+
3
+ Usage:
4
+ ppu-indra-ocr <command> [args] [flags]
5
+
6
+ Commands:
7
+ convert <file...> OCR images and PDFs (paths, globs, or http(s) URLs)
8
+ detect <image> Detect text lines only (JSON boxes to stdout)
9
+ download-models Pre-warm the model cache (~/.cache/ppu-indra-ocr)
10
+ clear-cache Delete the cached model files
11
+ models Print the model files, their URLs and the revision
12
+ help Show this help
13
+ version Show the installed version
14
+
15
+ Convert flags:
16
+ --format <f> md | text | json (default md; json is one object per page)
17
+ --out <dir> write one file per input (.md, .txt or .jsonl)
18
+ --math write math as LaTeX (loads 4 more models)
19
+ --keep-furniture keep page headers and footers in the markdown
20
+ --engine <e> opencv | canvas-native (default opencv)
21
+ --timings print per-page source and time to stderr
22
+
23
+ PDF flags:
24
+ --mode <m> auto | ocr | text (default auto: text layer where sound, OCR elsewhere)
25
+ --dpi <n> render resolution for OCR (default 200)
26
+ --max-pages <n> read at most n pages per PDF
27
+ --password <p> password for encrypted PDFs
28
+ --model-order order text-layer lines with the order model, not the PDF content order
29
+ --no-image-ocr on text-layer pages, do not OCR text inside images
30
+
31
+ Models and session:
32
+ --model-dir <dir> read the model files from a folder instead of downloading
33
+ --execution-providers <list> comma-separated, e.g. cpu or cuda,cpu (default cpu)
34
+
35
+ Output:
36
+ -o, --output <file> write everything to one file instead of stdout
37
+ --pretty indent JSON output
38
+ -q, --quiet suppress progress on stderr
39
+ --verbose log each step to stderr
40
+
41
+ Examples:
42
+ ppu-indra-ocr convert paper.pdf
43
+ ppu-indra-ocr convert "scans/*.png" --out results/
44
+ ppu-indra-ocr convert scan.png --format json --pretty
45
+ ppu-indra-ocr convert paper.pdf --mode ocr --math --timings
46
+ ppu-indra-ocr detect receipt.jpg
47
+
48
+ The model weights are Datalab's (https://huggingface.co/datalab-to/indra-ocr),
49
+ under a modified OpenRAIL-M license with use restrictions.
50
+ `;
package/cli/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/cli/index.js ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ process.on("SIGINT",()=>process.exit(130));try{const{main}=await import("./run.js");process.exit(await main(process.argv.slice(2)))}catch(e){let msg=e instanceof Error?e.message:String(e);if(msg.includes("onnxruntime-node")&&/cannot find (module|package)/i.test(msg)){process.stderr.write(`The 'onnxruntime-node' backend is not installed (optional peer dependency, ~258MB).
3
+ In a project: npm install ppu-indra-ocr onnxruntime-node
4
+ Zero-install: npx -p onnxruntime-node -p ppu-indra-ocr ppu-indra-ocr <args>
5
+ `);process.exit(1)}process.stderr.write(`${e instanceof Error?e.stack??msg:String(e)}
6
+ `);process.exit(1)}
package/cli/io.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /** A non-zero-exit error carrying the intended process exit code. */
2
+ export declare class CliError extends Error {
3
+ readonly code: number;
4
+ constructor(message: string, code?: number);
5
+ }
6
+ /** Throw a usage error (exit code 2). */
7
+ export declare function usageError(message: string): never;
8
+ /**
9
+ * Resolve a CLI image argument to an `ArrayBuffer`. The Node `recognize()`
10
+ * accepts only `ArrayBuffer`/`Canvas`, so URLs are fetched here and files read
11
+ * from disk - which also sidesteps the SDK's absolute-path-only string rule.
12
+ */
13
+ export declare function loadImageInput(arg: string): Promise<ArrayBuffer>;
14
+ /** True if a non-URL path is missing on disk. URLs are assumed reachable. */
15
+ export declare function isMissingLocalFile(arg: string): boolean;
16
+ /**
17
+ * Expand positional patterns into a concrete list. Glob patterns are resolved
18
+ * against the filesystem; plain paths and URLs pass through verbatim so a typo
19
+ * surfaces as a clear "No such file" later instead of silently vanishing.
20
+ */
21
+ export declare function expandPatterns(patterns: string[]): string[];
22
+ /** Walk up from this module to the nearest `ppu-indra-ocr` package.json. */
23
+ export declare function readVersion(): string;
24
+ /** Write `content` to a file (with trailing newline) or to stdout. */
25
+ export declare function writeOutput(content: string, outputPath?: string): void;
26
+ /** Log a line to stderr unless quiet. */
27
+ export declare function logStderr(message: string, quiet: boolean): void;
package/cli/io.js ADDED
@@ -0,0 +1,6 @@
1
+ import{existsSync,globSync,readFileSync,writeFileSync}from"node:fs";import{dirname,join}from"node:path";export class CliError extends Error{code;constructor(message,code=1){super(message);this.name="CliError";this.code=code}}export function usageError(message){throw new CliError(message,2)}let HTTP=/^https?:\/\//i;let GLOB_MAGIC=/[*?[\]{}]/;export async function loadImageInput(arg){if(HTTP.test(arg)){let res=await fetch(arg);if(!res.ok)throw new CliError(`Failed to fetch ${arg}: ${res.status} ${res.statusText}`);return res.arrayBuffer()}if(!existsSync(arg))throw new CliError(`No such file: ${arg}`);let buf=readFileSync(arg);return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}export function isMissingLocalFile(arg){return!HTTP.test(arg)&&!existsSync(arg)}export function expandPatterns(patterns){let out=[];for(let pattern of patterns){if(HTTP.test(pattern)||!GLOB_MAGIC.test(pattern)){out.push(pattern);continue}let matches=globSync(pattern).sort();if(matches.length===0)throw new CliError(`No files match: ${pattern}`);out.push(...matches)}return out}export function readVersion(){let injected=process.env.PPU_BINARY_VERSION;if(injected)return injected;let dir=import.meta.dirname;for(;;){let pkgPath=join(dir,"package.json");if(existsSync(pkgPath)){try{let pkg=JSON.parse(readFileSync(pkgPath,"utf-8"));if(pkg.name==="ppu-indra-ocr"&&pkg.version)return pkg.version}catch{}}let parent=dirname(dir);if(parent===dir)return"0.0.0";dir=parent}}export function writeOutput(content,outputPath){if(outputPath){writeFileSync(outputPath,content.endsWith(`
2
+ `)?content:`${content}
3
+ `);return}process.stdout.write(content.endsWith(`
4
+ `)?content:`${content}
5
+ `)}export function logStderr(message,quiet){if(!quiet)process.stderr.write(`${message}
6
+ `)}
@@ -0,0 +1,19 @@
1
+ import type { ParseArgsConfig } from "node:util";
2
+ import type { PdfPageOptions } from "../indra/document.js";
3
+ import type { IndraOptions } from "../interface.js";
4
+ /** `parseArgs` option spec shared by every command. */
5
+ export declare const PARSE_OPTIONS: NonNullable<ParseArgsConfig["options"]>;
6
+ /** Shape of `parseArgs().values` for the spec above. */
7
+ export type CliValues = Record<string, string | boolean | undefined>;
8
+ export type OutputFormat = "md" | "text" | "json";
9
+ /** A string flag's value, if given. */
10
+ export declare function str(values: CliValues, key: string): string | undefined;
11
+ /** Output format; md by default. */
12
+ export declare function format(values: CliValues): OutputFormat;
13
+ /** The service options from parsed flags. */
14
+ export declare function buildIndraOptions(values: CliValues): IndraOptions;
15
+ /** The PDF options from parsed flags. */
16
+ export declare function buildPdfOptions(values: CliValues): PdfPageOptions & {
17
+ maxPages?: number;
18
+ password?: string;
19
+ };
package/cli/options.js ADDED
@@ -0,0 +1 @@
1
+ import{join}from"node:path";import{MODEL_FILES}from"../model-catalogue.js";import{usageError}from"./io.js";export let PARSE_OPTIONS={format:{type:"string"},out:{type:"string"},mode:{type:"string"},math:{type:"boolean"},"keep-furniture":{type:"boolean"},dpi:{type:"string"},"max-pages":{type:"string"},password:{type:"string"},"model-order":{type:"boolean"},"no-image-ocr":{type:"boolean"},engine:{type:"string"},"model-dir":{type:"string"},"execution-providers":{type:"string"},timings:{type:"boolean"},output:{type:"string",short:"o"},pretty:{type:"boolean"},quiet:{type:"boolean",short:"q"},verbose:{type:"boolean"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}};export function str(values,key){let raw=values[key];return typeof raw==="string"?raw:undefined}function num(values,key){let raw=str(values,key);if(raw===undefined)return;let n=Number(raw);if(!Number.isFinite(n)||n<0)usageError(`--${key} must be a non-negative number, got "${raw}"`);return n}function oneOf(values,key,allowed){let raw=str(values,key);if(raw===undefined)return;let hit=allowed.find((a)=>a===raw);if(!hit)usageError(`--${key} must be one of ${allowed.join(" | ")}`);return hit}let ENGINES=["opencv","canvas-native"];let MODES=["auto","ocr","text"];let FORMATS=["md","text","json"];export function format(values){return oneOf(values,"format",FORMATS)??"md"}function modelDir(values){let dir=str(values,"model-dir");if(dir===undefined)return;let entries=Object.entries(MODEL_FILES).map(([role,file])=>[role,join(dir,file)]);return Object.fromEntries(entries)}function engine(values){let chosen=oneOf(values,"engine",ENGINES);if(!process.env.PPU_BINARY_SLIM)return chosen;if(chosen==="opencv")usageError("this slim binary has no OpenCV: use --engine canvas-native or the full binary");return"canvas-native"}export function buildIndraOptions(values){let providers=str(values,"execution-providers");return{models:modelDir(values),math:Boolean(values.math),furniture:Boolean(values["keep-furniture"]),engine:engine(values),session:providers?{executionProviders:providers.split(",").map((p)=>p.trim())}:undefined,verbose:Boolean(values.verbose)}}export function buildPdfOptions(values){return{mode:oneOf(values,"mode",MODES),dpi:num(values,"dpi"),pdfOrder:!values["model-order"],imageOcr:!values["no-image-ocr"],maxPages:num(values,"max-pages"),password:str(values,"password")}}
package/cli/run.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function main(argv: string[]): Promise<number>;
package/cli/run.js ADDED
@@ -0,0 +1,9 @@
1
+ import{parseArgs}from"node:util";import{runClearCache,runConvert,runDetect,runDownloadModels,runModels}from"./commands.js";import{USAGE}from"./help.js";import{CliError,readVersion}from"./io.js";import{PARSE_OPTIONS}from"./options.js";async function dispatch(command,rest,values){switch(command){case"convert":return runConvert(rest,values);case"detect":return runDetect(rest,values);case"download-models":return runDownloadModels(values);case"clear-cache":return runClearCache(values);case"models":return runModels(values);default:throw new CliError(`Unknown command: ${command}
2
+
3
+ ${USAGE}`,2)}}export async function main(argv){let parsed;try{parsed=parseArgs({args:argv,options:PARSE_OPTIONS,allowPositionals:true,strict:true})}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}
4
+
5
+ ${USAGE}`);return 2}let values=parsed.values;const[command,...rest]=parsed.positionals;if(values.version){process.stdout.write(`${readVersion()}
6
+ `);return 0}if(!command||command==="help"||values.help){process.stdout.write(USAGE);return 0}if(command==="version"){process.stdout.write(`${readVersion()}
7
+ `);return 0}try{await dispatch(command,rest,values);return 0}catch(e){if(e instanceof CliError){process.stderr.write(`${e.message}
8
+ `);return e.code}process.stderr.write(`${e instanceof Error?e.stack??e.message:String(e)}
9
+ `);return 1}}
@@ -0,0 +1,130 @@
1
+ /*! coi-serviceworker v0.1.7 - Guido Zuidhof and contributors, licensed under MIT */
2
+ // Injects COOP/COEP response headers so the page becomes cross-origin isolated,
3
+ // which enables SharedArrayBuffer and lets onnxruntime-web run multithreaded
4
+ // WASM. Needed because GitHub Pages cannot set these headers server-side.
5
+ let coepCredentialless = false;
6
+ if (typeof window === "undefined") {
7
+ self.addEventListener("install", () => self.skipWaiting());
8
+ self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()));
9
+
10
+ self.addEventListener("message", (ev) => {
11
+ if (!ev.data) {
12
+ return;
13
+ } else if (ev.data.type === "deregister") {
14
+ self.registration
15
+ .unregister()
16
+ .then(() => self.clients.matchAll())
17
+ .then((clients) => clients.forEach((client) => client.navigate(client.url)));
18
+ } else if (ev.data.type === "coepCredentialless") {
19
+ coepCredentialless = ev.data.value;
20
+ }
21
+ });
22
+
23
+ self.addEventListener("fetch", function (event) {
24
+ const r = event.request;
25
+ if (r.cache === "only-if-cached" && r.mode !== "same-origin") {
26
+ return;
27
+ }
28
+
29
+ const request =
30
+ coepCredentialless && r.mode === "no-cors" ? new Request(r, { credentials: "omit" }) : r;
31
+ event.respondWith(
32
+ fetch(request)
33
+ .then((response) => {
34
+ if (response.status === 0) {
35
+ return response;
36
+ }
37
+
38
+ const newHeaders = new Headers(response.headers);
39
+ newHeaders.set(
40
+ "Cross-Origin-Embedder-Policy",
41
+ coepCredentialless ? "credentialless" : "require-corp"
42
+ );
43
+ if (!coepCredentialless) {
44
+ newHeaders.set("Cross-Origin-Resource-Policy", "cross-origin");
45
+ }
46
+ newHeaders.set("Cross-Origin-Opener-Policy", "same-origin");
47
+
48
+ return new Response(response.body, {
49
+ status: response.status,
50
+ statusText: response.statusText,
51
+ headers: newHeaders,
52
+ });
53
+ })
54
+ .catch((e) => console.error(e))
55
+ );
56
+ });
57
+ } else {
58
+ (() => {
59
+ const reloadedBySelf = window.sessionStorage.getItem("coiReloadedBySelf");
60
+ window.sessionStorage.removeItem("coiReloadedBySelf");
61
+ const coepDegrading = reloadedBySelf == "coepdegrade";
62
+
63
+ // You can customize the behavior of this script through a global `coi` variable.
64
+ const coi = {
65
+ shouldRegister: () => !reloadedBySelf,
66
+ shouldDeregister: () => false,
67
+ coepCredentialless: () => true,
68
+ coepDegrade: () => true,
69
+ doReload: () => window.location.reload(),
70
+ quiet: false,
71
+ ...window.coi,
72
+ };
73
+
74
+ const n = navigator;
75
+ const controlling = n.serviceWorker && n.serviceWorker.controller;
76
+
77
+ // Record the failure if the page is served by serviceWorker.
78
+ if (controlling && !window.crossOriginIsolated) {
79
+ window.sessionStorage.setItem("coiCoepHasFailed", "true");
80
+ }
81
+ const coepHasFailed = window.sessionStorage.getItem("coiCoepHasFailed");
82
+
83
+ if (controlling) {
84
+ // Reload only on the first failure.
85
+ const reloadToDegrade = coi.coepDegrade() && !(coepDegrading || window.crossOriginIsolated);
86
+ n.serviceWorker.controller.postMessage({
87
+ type: "coepCredentialless",
88
+ value:
89
+ reloadToDegrade || (coepHasFailed && coi.coepDegrade())
90
+ ? false
91
+ : coi.coepCredentialless(),
92
+ });
93
+ if (reloadToDegrade) {
94
+ !coi.quiet && console.log("Reloading page to degrade COEP.");
95
+ window.sessionStorage.setItem("coiReloadedBySelf", "coepdegrade");
96
+ coi.doReload("coepdegrade");
97
+ }
98
+ } else if (coi.shouldRegister()) {
99
+ if (!window.isSecureContext) {
100
+ !coi.quiet &&
101
+ console.log("COOP/COEP Service Worker not registered, a secure context is required.");
102
+ } else {
103
+ n.serviceWorker &&
104
+ n.serviceWorker.register(window.document.currentScript.src).then(
105
+ (registration) => {
106
+ !coi.quiet && console.log("COOP/COEP Service Worker registered", registration.scope);
107
+
108
+ registration.addEventListener("updatefound", () => {
109
+ !coi.quiet &&
110
+ console.log("Reloading page to make use of updated COOP/COEP Service Worker.");
111
+ window.sessionStorage.setItem("coiReloadedBySelf", "updatefound");
112
+ coi.doReload();
113
+ });
114
+
115
+ // If the registration is active, but it's not controlling the page
116
+ if (registration.active && !n.serviceWorker.controller) {
117
+ !coi.quiet &&
118
+ console.log("Reloading page to make use of COOP/COEP Service Worker.");
119
+ window.sessionStorage.setItem("coiReloadedBySelf", "notcontrolling");
120
+ coi.doReload();
121
+ }
122
+ },
123
+ (err) => {
124
+ !coi.quiet && console.error("COOP/COEP Service Worker failed to register:", err);
125
+ }
126
+ );
127
+ }
128
+ }
129
+ })();
130
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Bounded-concurrency orchestration used by `batchRecognize` /
3
+ * `batchRecognizeStream`. Kept platform-agnostic and free of any OCR types so
4
+ * it can be unit-tested in isolation.
5
+ */
6
+ /** A single settled batch item, tagged with its input index. */
7
+ export type BatchItemResult<T> = {
8
+ index: number;
9
+ status: "fulfilled";
10
+ value: T;
11
+ } | {
12
+ index: number;
13
+ status: "rejected";
14
+ reason: unknown;
15
+ };
16
+ /** Controls how {@link runPool} schedules and settles work. */
17
+ export type RunPoolOptions = {
18
+ /** Maximum number of tasks in flight at once. Clamped to >= 1. */
19
+ concurrency: number;
20
+ /** When `true`, per-item rejections are reported instead of aborting the run. */
21
+ settle: boolean;
22
+ /** Cancels scheduling of further items; the run rejects with an `AbortError`. */
23
+ signal?: AbortSignal;
24
+ /** Invoked after each item settles, with the running done count and total (if known). */
25
+ onProgress?: (done: number, total: number | undefined) => void;
26
+ /** Total item count when the input length is known up front. */
27
+ total?: number;
28
+ };
29
+ /**
30
+ * Run `task` over `inputs` with at most `concurrency` tasks in flight,
31
+ * invoking `onSettle` as each item finishes (in completion order, each tagged
32
+ * with its input index for reordering).
33
+ *
34
+ * Resolves once every item has settled. With `settle: false` it rejects on the
35
+ * first task error after halting further scheduling; with `settle: true` every
36
+ * item is delivered to `onSettle` and the run only rejects on abort. Honors
37
+ * `signal` by ceasing to schedule new items (in-flight tasks are not forcibly
38
+ * cancelled, but their results are dropped).
39
+ */
40
+ export declare function runPool<I, O>(inputs: Iterable<I> | AsyncIterable<I>, options: RunPoolOptions, task: (item: I, index: number) => Promise<O>, onSettle: (result: BatchItemResult<O>) => void): Promise<void>;
41
+ /** Producer handle plus the consumer's drain, for {@link createAsyncQueue}. */
42
+ export type AsyncQueue<T> = {
43
+ push: (item: T) => void;
44
+ close: () => void;
45
+ fail: (error: unknown) => void;
46
+ drain: () => AsyncGenerator<T>;
47
+ };
48
+ /**
49
+ * A minimal single-consumer async queue: producers `push` settled items, the
50
+ * consumer drains them as an async iterable. Bridges {@link runPool}'s callback
51
+ * model to `batchRecognizeStream`'s generator.
52
+ */
53
+ export declare function createAsyncQueue<T>(): AsyncQueue<T>;
package/core/batch.js ADDED
@@ -0,0 +1 @@
1
+ function toAbortError(signal){return signal.reason instanceof Error?signal.reason:new DOMException("The batch operation was aborted.","AbortError")}function toAsyncIterator(inputs){if(Symbol.asyncIterator in inputs){return inputs[Symbol.asyncIterator]()}let sync=inputs[Symbol.iterator]();return{next:()=>Promise.resolve(sync.next()),return:(value)=>Promise.resolve(sync.return?.(value)??{done:true,value:undefined})}}export async function runPool(inputs,options,task,onSettle){const{settle,signal}=options;let concurrency=Math.max(1,Math.floor(options.concurrency));if(signal?.aborted)throw toAbortError(signal);let nextIndex=0;let done=0;let stopped=false;let failed=false;let failure;let array=Array.isArray(inputs)?inputs:null;let iterator=array?null:toAsyncIterator(inputs);let lock=Promise.resolve();let nextItem=async()=>{let previous=lock;let release;lock=new Promise((resolve)=>{release=resolve});await previous;try{return await iterator.next()}finally{release()}};let onAbort=()=>{stopped=true};signal?.addEventListener("abort",onAbort,{once:true});let worker=async()=>{while(!stopped){let item;let index;if(array){if(nextIndex>=array.length)return;index=nextIndex++;item=array[index]}else{let next=await nextItem();if(next.done||stopped)return;index=nextIndex++;item=next.value}try{let value=await task(item,index);if(stopped)return;onSettle({index,status:"fulfilled",value})}catch(reason){if(settle){onSettle({index,status:"rejected",reason})}else{stopped=true;failed=true;failure=reason;return}}finally{done++;options.onProgress?.(done,options.total)}}};try{await Promise.all(Array.from({length:concurrency},()=>worker()))}finally{signal?.removeEventListener("abort",onAbort);await iterator?.return?.()}if(signal?.aborted)throw toAbortError(signal);if(failed)throw failure}export function createAsyncQueue(){let items=[];let wake=null;let closed=false;let failure=null;let notify=()=>{let w=wake;wake=null;w?.()};return{push(item){items.push(item);notify()},close(){closed=true;notify()},fail(error){failure={error};closed=true;notify()},async*drain(){while(true){while(items.length>0){yield items.shift()}if(failure)throw failure.error;if(closed)return;await new Promise((resolve)=>{wake=resolve})}}}}
@@ -0,0 +1,65 @@
1
+ import type { DetBox } from "../indra/det-post.js";
2
+ import type { Gray } from "../indra/image.js";
3
+ import type { MathReading } from "../indra/math.js";
4
+ import { IndraPipeline } from "../indra/pipeline.js";
5
+ import type { Box } from "../indra/rec-preproc.js";
6
+ import type { Orientation, Page, ReadingOrder, RecLine, Straightened } from "../indra/types.js";
7
+ import type { BatchOptions, IndraOptions, ProcessingEngine } from "../interface.js";
8
+ import type { BatchItemResult } from "./batch.js";
9
+ import type { CoreCanvas, PlatformProvider } from "./platform.js";
10
+ /** An image to read: encoded bytes (PNG, JPEG, ...), a platform canvas, or 8-bit gray pixels. */
11
+ export type ImageInput<TCanvas = CoreCanvas> = ArrayBuffer | Uint8Array | TCanvas | Gray;
12
+ /**
13
+ * Indra OCR on one platform. Call `initialize()` once, then `convert()` a page,
14
+ * or run the stages yourself: `orient`, `straighten`, `detect`, `recognize`,
15
+ * `order`, `readMath`. Call `destroy()` to release the models.
16
+ */
17
+ export declare abstract class BaseIndraOcrService<TCanvas = CoreCanvas> {
18
+ protected readonly platform: PlatformProvider<TCanvas>;
19
+ protected readonly options: IndraOptions;
20
+ private indra;
21
+ private sessions;
22
+ private engineInUse;
23
+ protected constructor(platform: PlatformProvider<TCanvas>, options?: IndraOptions);
24
+ protected log(message: string): void;
25
+ isInitialized(): boolean;
26
+ /** The engine in use after initialize(). */
27
+ get engine(): ProcessingEngine | null;
28
+ /** The stage pipeline. Throws before initialize(). */
29
+ get pipeline(): IndraPipeline;
30
+ /** Load the models (and OpenCV for the opencv engine). Safe to call twice. */
31
+ initialize(): Promise<void>;
32
+ private load;
33
+ private imageOps;
34
+ /** Release the models. The service can be initialized again. */
35
+ destroy(): Promise<void>;
36
+ /** 8-bit gray pixels of an image (OpenCV's BT.601 weights for color). */
37
+ toGray(image: ImageInput<TCanvas>): Promise<Gray>;
38
+ /** OCR of one page image: markdown, text, lines and layout blocks. */
39
+ convert(image: ImageInput<TCanvas>): Promise<Page>;
40
+ /** Convert many images. Results keep the input order. */
41
+ convertBatch(images: Iterable<ImageInput<TCanvas>> | AsyncIterable<ImageInput<TCanvas>>, options: BatchOptions & {
42
+ settle: true;
43
+ }): Promise<BatchItemResult<Page>[]>;
44
+ convertBatch(images: Iterable<ImageInput<TCanvas>> | AsyncIterable<ImageInput<TCanvas>>, options?: BatchOptions): Promise<Page[]>;
45
+ /** Convert many images, yielding each result as it finishes (completion order). */
46
+ convertStream(images: Iterable<ImageInput<TCanvas>> | AsyncIterable<ImageInput<TCanvas>>, options?: BatchOptions): AsyncGenerator<BatchItemResult<Page>>;
47
+ private poolOptions;
48
+ /** Quarter turns (counter-clockwise) the content is turned by, from orient.onnx. */
49
+ orient(image: ImageInput<TCanvas>): Promise<Orientation>;
50
+ /** The page turned upright by `turns` quarter turns and deskewed. */
51
+ straighten(image: ImageInput<TCanvas>, turns?: number): Promise<Straightened>;
52
+ /** Line boxes (x0, y0, x1, y1, score) in image pixels. */
53
+ detect(image: ImageInput<TCanvas>): Promise<DetBox[]>;
54
+ /**
55
+ * Text, confidence and character positions of each box, one line per box.
56
+ * Boxes should hug the text: the recognizer adds 0.2 x the box height above
57
+ * and below and 0.3 x on each side. A box from another detector that carries
58
+ * its own padding shrinks the text and reads worse; trim it first.
59
+ */
60
+ recognize(image: ImageInput<TCanvas>, boxes: readonly Box[]): Promise<RecLine[]>;
61
+ /** Reading order of lines, with the layout heads' class and same-block logits. */
62
+ order(boxes: readonly Box[], texts: readonly string[], width: number, height: number): Promise<ReadingOrder>;
63
+ /** Math readings (text with inline LaTeX, mean token probability) of the boxes. Needs `math: true`. */
64
+ readMath(image: ImageInput<TCanvas>, boxes: readonly Box[]): Promise<MathReading[]>;
65
+ }
@@ -0,0 +1 @@
1
+ export class BaseIndraOcrService{platform;options;indra=null;sessions=[];engineInUse=null;constructor(platform,options={}){this.platform=platform;this.options={...options}}log(message){if(this.options.verbose)console.log(`[IndraOcrService] ${message}`)}isInitialized(){return this.indra!==null}get engine(){return this.engineInUse}get pipeline(){if(!this.indra)throw new Error("IndraOcrService is not initialized: call initialize() first");return this.indra}async initialize(){if(this.indra)return;let roles=this.options.math?[...BASE_FILES,...MATH_FILES]:BASE_FILES;let bytes=new Map(await Promise.all(roles.map(async(role)=>[role,await this.load(role)])));let text=(role)=>new TextDecoder().decode(bytes.get(role));let session=async(role)=>{let s=await createSessionWithFallback(this.platform.ort,new Uint8Array(bytes.get(role)??new ArrayBuffer(0)),this.options.session,(msg)=>this.log(msg),(next)=>this.options.session=next);this.sessions.push(s);return s};let ops=await this.imageOps();let meta=JSON.parse(text("meta"));let math=this.options.math?new MathReader(this.platform.ort.Tensor,{cls:await session("mathCls"),enc:await session("mathEnc"),init:await session("mathDecInit"),step:await session("mathDecStep")},JSON.parse(text("mathMeta")),ops):undefined;this.indra=new IndraPipeline(this.platform.ort.Tensor,{det:await session("det"),rec:await session("rec"),recCjk:await session("recCjk"),script:await session("script"),orient:await session("orient"),order:await session("order")},meta,ops,{furniture:this.options.furniture,adaptive:this.options.adaptive,math});this.log(`ready: ${roles.length} model files, engine ${this.engineInUse}`)}async load(role){let source=this.options.models?.[role];try{return await this.platform.loadResource(source,defaultModelUrl(role))}catch(err){let from=source instanceof ArrayBuffer?"the given bytes":source??defaultModelUrl(role);let msg=err instanceof Error?err.message:String(err);throw new Error(`could not load ${MODEL_FILES[role]} from ${from}: ${msg}`,{cause:err})}}async imageOps(){let opencv=this.platform.opencv;let engine=this.options.engine??this.platform.defaultEngine;this.engineInUse=engine;if(engine==="canvas-native")return tsImageOps;if(!opencv)throw new Error('the "opencv" engine is not available on this platform');return opencvImageOps(await opencv())}async destroy(){await Promise.all(this.sessions.map((s)=>s.release()));this.sessions=[];this.indra=null}async toGray(image){if(isGray(image))return image;if(this.platform.isCanvas(image))return grayFromRgba(this.platform.pixels(image));if(image instanceof ArrayBuffer||image instanceof Uint8Array){let buf=image instanceof Uint8Array?image.buffer.slice(image.byteOffset,image.byteOffset+image.byteLength):image;let canvas=await this.platform.decodeImage(buf);return grayFromRgba(this.platform.pixels(canvas))}throw new TypeError("image must be encoded bytes, a canvas, or { data, width, height } gray pixels")}async convert(image){return this.pipeline.page(await this.toGray(image))}async convertBatch(images,options={}){let collected=[];await runPool(images,this.poolOptions(images,options),(image)=>this.convert(image),(r)=>{collected[r.index]=r});if(options.settle)return collected;return collected.flatMap((r)=>r.status==="fulfilled"?[r.value]:[])}async*convertStream(images,options={}){let queue=createAsyncQueue();let pump=(async()=>{try{await runPool(images,this.poolOptions(images,options),(image)=>this.convert(image),(r)=>queue.push(r));queue.close()}catch(error){queue.fail(error)}})();yield*queue.drain();await pump}poolOptions(images,options){return{concurrency:options.concurrency??1,settle:options.settle??false,signal:options.signal,onProgress:options.onProgress,total:Array.isArray(images)?images.length:undefined}}async orient(image){return this.pipeline.orient(await this.toGray(image))}async straighten(image,turns=0){return this.pipeline.straighten(await this.toGray(image),turns)}async detect(image){return this.pipeline.detect(await this.toGray(image))}async recognize(image,boxes){return this.pipeline.recognize(await this.toGray(image),boxes)}async order(boxes,texts,width,height){return this.pipeline.readingOrder(boxes,texts,width,height)}async readMath(image,boxes){let math=this.pipeline.mathReader;if(!math)throw new Error("readMath needs the service created with { math: true }");return math.read(await this.toGray(image),boxes)}}import{grayFromRgba}from"../indra/image.js";import{MathReader}from"../indra/math.js";import{IndraPipeline}from"../indra/pipeline.js";import{tsImageOps}from"../indra/ts-image-ops.js";import{BASE_FILES,MATH_FILES,MODEL_FILES,defaultModelUrl}from"../model-catalogue.js";import{createAsyncQueue,runPool}from"./batch.js";import{opencvImageOps}from"./opencv-image-ops.js";import{createSessionWithFallback}from"./session-factory.js";function isGray(image){return typeof image==="object"&&image!==null&&"data"in image&&image.data instanceof Uint8Array&&"width"in image&&"height"in image&&image.data.length===Number(image.width)*Number(image.height)}
@@ -0,0 +1,5 @@
1
+ /** Run one operation with a newly initialized service, then release it. */
2
+ export declare function runOneShot<TService extends {
3
+ initialize(): Promise<void>;
4
+ destroy(): Promise<void>;
5
+ }, TResult>(createService: () => TService, run: (service: TService) => Promise<TResult>): Promise<TResult>;
@@ -0,0 +1 @@
1
+ export async function runOneShot(createService,run){let service=createService();try{await service.initialize();return await run(service)}finally{await service.destroy()}}
@@ -0,0 +1,10 @@
1
+ import type { cv as CvNamespace } from "ppu-ocv";
2
+ import type { ImageOps } from "../indra/image.js";
3
+ type Cv = typeof CvNamespace;
4
+ /**
5
+ * ImageOps on OpenCV.js. The reference runs the same OpenCV release (5.0.0)
6
+ * through cv2, so these calls give the same bytes as the Python pipeline.
7
+ * Every Mat is deleted before return: OpenCV.js memory is not garbage collected.
8
+ */
9
+ export declare function opencvImageOps(cv: Cv): ImageOps;
10
+ export {};
@@ -0,0 +1 @@
1
+ export function opencvImageOps(cv){let interp=(i)=>i==="area"?cv.INTER_AREA:cv.INTER_LINEAR;let grayMat=(src)=>{let mat=new cv.Mat(src.height,src.width,cv.CV_8UC1);mat.data.set(src.data);return mat};let affineMat=(m)=>cv.matFromArray(2,3,cv.CV_64FC1,m);return{resize(src,width,height,interpolation){let from=grayMat(src);let to=new cv.Mat;try{cv.resize(from,to,new cv.Size(width,height),0,0,interp(interpolation));return{data:new Uint8Array(to.data),width,height}}finally{from.delete();to.delete()}},warpReplicate(src,m,width,height){let from=grayMat(src);let to=new cv.Mat;let mat=affineMat(m);try{cv.warpAffine(from,to,mat,new cv.Size(width,height),cv.INTER_LINEAR,cv.BORDER_REPLICATE);return{data:new Uint8Array(to.data),width,height}}finally{from.delete();to.delete();mat.delete()}},warpFloat(src,m,width,height){let from=new cv.Mat(src.height,src.width,cv.CV_32FC1);from.data32F.set(src.data);let to=new cv.Mat;let mat=affineMat(m);try{cv.warpAffine(from,to,mat,new cv.Size(width,height));return{data:new Float32Array(to.data32F),width,height}}finally{from.delete();to.delete();mat.delete()}}}}
@@ -0,0 +1,40 @@
1
+ import type { InferenceSession, Tensor } from "onnxruntime-common";
2
+ import type { Canvas, cv } from "ppu-ocv";
3
+ import type { CanvasLike } from "ppu-ocv/web";
4
+ import type { ProcessingEngine } from "../interface.js";
5
+ /** A canvas from any supported platform: node-canvas, HTML canvas, OffscreenCanvas, Skia. */
6
+ export type CoreCanvas = Canvas | CanvasLike;
7
+ /** The OpenCV.js namespace. */
8
+ export type Cv = typeof cv;
9
+ /** RGBA pixels, row-major, 4 bytes per pixel. */
10
+ export type Rgba = {
11
+ data: ArrayLike<number>;
12
+ width: number;
13
+ height: number;
14
+ };
15
+ /**
16
+ * What the platform-free service needs from a runtime: ONNX Runtime, image
17
+ * decoding, resource loading, and OpenCV where it loads.
18
+ */
19
+ export type PlatformProvider<TCanvas = CoreCanvas> = {
20
+ /** The platform's ONNX Runtime (`onnxruntime-node`, `-web` or `-react-native`). */
21
+ ort: {
22
+ Tensor: typeof Tensor;
23
+ InferenceSession: typeof InferenceSession;
24
+ };
25
+ /** Whether a value is this platform's canvas. */
26
+ isCanvas: (image: unknown) => image is TCanvas;
27
+ /** Decode encoded image bytes (PNG, JPEG, WebP, ...) into a canvas. */
28
+ decodeImage: (bytes: ArrayBuffer) => Promise<TCanvas>;
29
+ /** The RGBA pixels of a canvas. */
30
+ pixels: (canvas: TCanvas) => Rgba;
31
+ /**
32
+ * A model file's bytes: `source` itself, a path or URL to read (cached
33
+ * where the platform can), or `defaultUrl` when `source` is undefined.
34
+ */
35
+ loadResource: (source: string | ArrayBuffer | undefined, defaultUrl: string) => Promise<ArrayBuffer>;
36
+ /** OpenCV.js, initialized. Undefined where OpenCV is not available (React Native). */
37
+ opencv?: () => Promise<Cv>;
38
+ /** The engine when the options name none: "opencv" on Node, "canvas-native" where OpenCV.js is a large download. */
39
+ defaultEngine: ProcessingEngine;
40
+ };
@@ -0,0 +1,23 @@
1
+ import type { InferenceSession } from "onnxruntime-common";
2
+ import type { SessionOptions } from "../interface.js";
3
+ /** Minimal shape of an ORT namespace capable of creating sessions. */
4
+ export type OrtLike = {
5
+ InferenceSession: typeof InferenceSession;
6
+ };
7
+ /**
8
+ * Create an ORT session, retrying with a CPU/WASM-only provider list if the
9
+ * original attempt fails.
10
+ *
11
+ * Works around cases like `executionProviders: ["cuda", "cpu"]` on a host
12
+ * without the CUDA runtime - ORT throws during session construction instead
13
+ * of silently falling back to CPU. We catch that, log once, and retry with
14
+ * whichever safe provider (`cpu` or `wasm`) was in the original list (or
15
+ * default to `cpu` / `wasm` based on the ORT binding shape).
16
+ *
17
+ * Throws the original error if the provider list was already safe-only.
18
+ *
19
+ * `sessionOpts.onSessionFallback` is stripped before the options reach ORT and
20
+ * is called with the original error once the fallback session is ready, so a
21
+ * host that runs its own accelerator ladder can see the silent degradation.
22
+ */
23
+ export declare function createSessionWithFallback(ort: OrtLike, modelData: Uint8Array, sessionOpts: SessionOptions | undefined, logger: (msg: string) => void, onFallback?: (newOpts: SessionOptions) => void): Promise<InferenceSession>;
@@ -0,0 +1 @@
1
+ let ALWAYS_AVAILABLE_FALLBACKS=new Set(["cpu","wasm"]);function providerName(provider){return typeof provider==="string"?provider:provider.name}export async function createSessionWithFallback(ort,modelData,sessionOpts,logger,onFallback){const{onSessionFallback,...given}=sessionOpts??{};let opts={enableCpuMemArena:false,...given};try{return await ort.InferenceSession.create(modelData,opts)}catch(err){let providers=opts.executionProviders??[];let names=providers.map(providerName);let alreadySafe=names.every((n)=>ALWAYS_AVAILABLE_FALLBACKS.has(n));if(alreadySafe||names.length===0){throw err}let fallback=names.find((n)=>ALWAYS_AVAILABLE_FALLBACKS.has(n));let fallbackName=fallback??(names.includes("wasm")?"wasm":"cpu");let msg=err instanceof Error?err.message:String(err);logger(`executionProviders=${JSON.stringify(names)} failed (${msg}); `+`falling back to ["${fallbackName}"].`);let fallbackOpts={...opts,executionProviders:[fallbackName]};onFallback?.({...fallbackOpts,onSessionFallback});let session=await ort.InferenceSession.create(modelData,fallbackOpts);onSessionFallback?.(err);return session}}
package/exports.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ export type { BatchItemResult } from "./core/batch.js";
2
+ export type { ImageInput } from "./core/indra-ocr.service.js";
3
+ export type { DetBox } from "./indra/det-post.js";
4
+ export { isPdf } from "./indra/document.js";
5
+ export type { Gray } from "./indra/image.js";
6
+ export type { Cell, LayoutBlock } from "./indra/layout-post.js";
7
+ export { joinLines, pageMarkdown as toMarkdown } from "./indra/layout-post.js";
8
+ export type { MathReading } from "./indra/math.js";
9
+ export { BLOCK_CLASSES, orderXYCut } from "./indra/order-post.js";
10
+ export type { BlockLabel } from "./indra/order-post.js";
11
+ export type { Box } from "./indra/rec-preproc.js";
12
+ export type { Line, Orientation, Page, PageSource, ReadingOrder, RecLine, Straightened, Tok, } from "./indra/types.js";
13
+ export type { BatchOptions, IndraOptions, ModelSources, ProcessingEngine, SessionOptions, } from "./interface.js";
14
+ export { MATH_FILES, MODEL_BASE_URL, MODEL_FILES, MODEL_MIRROR_BASE_URL, MODEL_REVISION, defaultModelUrl, } from "./model-catalogue.js";
15
+ export type { ModelFile } from "./model-catalogue.js";
package/exports.js ADDED
@@ -0,0 +1 @@
1
+ export{isPdf}from"./indra/document.js";export{joinLines,pageMarkdown as toMarkdown}from"./indra/layout-post.js";export{BLOCK_CLASSES,orderXYCut}from"./indra/order-post.js";export{MATH_FILES,MODEL_BASE_URL,MODEL_FILES,MODEL_MIRROR_BASE_URL,MODEL_REVISION,defaultModelUrl}from"./model-catalogue.js";
package/index.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { ImageInput } from "./core/indra-ocr.service.js";
2
+ import type { DetBox } from "./indra/det-post.js";
3
+ import type { Page } from "./indra/types.js";
4
+ import type { IndraOptions } from "./interface.js";
5
+ import { IndraOcrService } from "./processor/indra-ocr.service.js";
6
+ export * from "./exports.js";
7
+ export { IndraOcrService };
8
+ /** OCR one image without managing a service: load the models, convert, release. */
9
+ export declare function ocr(image: ImageInput, options?: IndraOptions): Promise<Page>;
10
+ /** Detect the text lines of one image without managing a service. */
11
+ export declare function detect(image: ImageInput, options?: IndraOptions): Promise<DetBox[]>;
package/index.js ADDED
@@ -0,0 +1 @@
1
+ import{runOneShot}from"./core/one-shot.js";import{IndraOcrService}from"./processor/indra-ocr.service.js";export*from"./exports.js";export{IndraOcrService};export function ocr(image,options){return runOneShot(()=>new IndraOcrService(options),(service)=>service.convert(image))}export function detect(image,options){return runOneShot(()=>new IndraOcrService(options),(service)=>service.detect(image))}
@@ -0,0 +1,22 @@
1
+ import type { Box } from "./rec-preproc.js";
2
+ import type { LinePart, Page, ReadingOrder, RecLine } from "./types.js";
3
+ import type { Vocab } from "./vocab.js";
4
+ /** A line part with the confidence of the line it came from. */
5
+ export type Part = LinePart & {
6
+ conf: number;
7
+ };
8
+ /** Lines split at wide gaps and column gutters (SPLIT_GAP), the way text-layer labels split them. */
9
+ export declare function splitParts(vocab: Vocab, boxes: readonly Box[], rec: readonly RecLine[]): Part[];
10
+ /** A reading order and how it was chosen. */
11
+ export type ChosenOrder = {
12
+ order: number[];
13
+ note: string;
14
+ };
15
+ /**
16
+ * Keep the PDF content order when every part comes from the text layer and
17
+ * that order is coherent (few upward jumps, the order model agrees with most
18
+ * neighbours); otherwise the model's order.
19
+ */
20
+ export declare function chooseOrder(parts: readonly Part[], ro: ReadingOrder, contentOrder: boolean): ChosenOrder;
21
+ /** The page from ordered line parts: output lines, blocks and markdown. */
22
+ export declare function buildPage(vocab: Vocab, parts: readonly Part[], { cls, same }: ReadingOrder, { order, note }: ChosenOrder, furniture: boolean, t: Record<string, number>): Page;
@@ -0,0 +1,3 @@
1
+ import{pageBlocks,pageMarkdown}from"./layout-post.js";import{CELL_GAP,SPLIT_GAP,gutterCuts,splitLine}from"./lines.js";import{pdfOrderCoherent}from"./textlayer.js";import{roundTo}from"./upright.js";import{item}from"./util.js";function f32Box([x0,y0,x1,y1]){let f=Math.fround;return[f(x0),f(y0),f(x1),f(y1)]}export function splitParts(vocab,boxes,rec){let cuts=gutterCuts(vocab,boxes,rec);return boxes.flatMap((b,i)=>splitLine(vocab,b,item(rec,i).toks,SPLIT_GAP,item(cuts,i)).map((p)=>({...p,box:f32Box(p.box),conf:item(rec,i).conf})))}export function chooseOrder(parts,ro,contentOrder){let n=parts.length;if(contentOrder&&n>1){let keys=parts.map((p)=>{let idx=p.toks.flatMap((tk)=>tk[2]===undefined?[]:[tk[2]]);return idx.length?Math.min(...idx):undefined});if(keys.every((k)=>k!==undefined)){let pdf=keys.map((_,i)=>i).toSorted((a,b)=>(keys[a]??0)-(keys[b]??0));let logits=ro.logits;let sub=logits?Float32Array.from({length:n*n},(_,k)=>logits[item(pdf,Math.floor(k/n))*n+item(pdf,k%n)]??0):undefined;if(pdfOrderCoherent(pdf.map((i)=>item(parts,i).box),sub))return{order:pdf,note:"order=pdf"}}}return{order:ro.order,note:"order=model"}}export function buildPage(vocab,parts,{cls,same},{order,note},furniture,t){t["total_ms"]=Object.entries(t).reduce((sum,[k,v])=>k==="total_ms"?sum:sum+v,0);let boxes=parts.map((p)=>p.box);let texts=parts.map((p)=>p.text);let lines=order.map((i)=>{let p=item(parts,i);const[x0,y0,x1,y1]=p.box;return{box:[roundTo(x0,1),roundTo(y0,1),roundTo(x1,1),roundTo(y1,1)],text:p.text,conf:roundTo(p.conf,4)}});let markdown=null;let blocks=[];if(cls&&same){blocks=pageBlocks(boxes,texts,order,cls,same);let cells=new Map(parts.map((p,i)=>[i,splitLine(vocab,p.box,p.toks,CELL_GAP).map(({box,text})=>({box,text}))]));markdown=pageMarkdown(boxes,texts,order,cls,same,furniture,cells)}else if(parts.length<2){markdown=texts.join(`
2
+ `)}return{lines,text:lines.map((l)=>l.text).join(`
3
+ `),markdown,blocks,source:"ocr",note,rotation:0,skew:0,timings:t}}