pdf-vizyr 0.0.0-stage → 0.1.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/CHANGELOG.md +21 -0
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/dist/index.js +69 -0
- package/dist/index.js.map +7 -0
- package/dist/index.min.js +2 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/read.d.ts +16 -0
- package/package.json +76 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `pdf-vizyr` are written here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the package follows
|
|
5
|
+
[Semantic Versioning](https://semver.org/spec/v2.0.0.html): before 1.0, a minor version may break the published
|
|
6
|
+
surface, a patch never does. Dates are the publication dates on the npm registry (UTC).
|
|
7
|
+
|
|
8
|
+
## [0.1.0] - 2026-12-02
|
|
9
|
+
|
|
10
|
+
First version: the AI reading of scanned PDF pages, out of `pdf-skryba` (which no longer reads with a model since its
|
|
11
|
+
3.0.0), on pdf-skryba's `pages` entry.
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- `readPdfWithVision(bytes, reader, options?)`, `readScannedPages(bytes, pageIndices, reader, options?)`,
|
|
16
|
+
`textToParagraphs(text)`, `OCR_BATCH_MAX_BYTES`; types `PdfVisionOptions`, `PageTextReader`, `PageText`,
|
|
17
|
+
`PdfReading`.
|
|
18
|
+
- The batches are sliced by pdf-skryba's own PDF writer (`copyPdfPages`), no longer by `@cantoo/pdf-lib`, which opened
|
|
19
|
+
the whole file with none of the reader's bounds.
|
|
20
|
+
|
|
21
|
+
[0.1.0]: https://www.npmjs.com/package/pdf-vizyr/v/0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MIKSUMIA
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,68 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pdf-vizyr
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Reads the scanned pages of a PDF with an AI model of your own, and gives the whole document back, page by page.
|
|
4
|
+
|
|
5
|
+
It builds on [pdf-skryba](https://www.npmjs.com/package/pdf-skryba), which reads the digital text of a PDF and tells
|
|
6
|
+
which pages have none. pdf-vizyr sends those pages to your model in small batches, checks what comes back, and composes
|
|
7
|
+
the document again in page order: one tab per page, read or transcribed alike.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install pdf-vizyr
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
ES modules only, for Node.js 24 or later; the types ship with the package.
|
|
16
|
+
|
|
17
|
+
## Example
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { readFileSync } from "node:fs";
|
|
21
|
+
import { readPdfWithVision, type PageTextReader } from "pdf-vizyr";
|
|
22
|
+
|
|
23
|
+
// Your model: it receives a small PDF holding the pages to read, and returns one { text, confidence } per page, in
|
|
24
|
+
// order. This document has text on every page, so it is never called.
|
|
25
|
+
const reader: PageTextReader = {
|
|
26
|
+
readPages: () => Promise.reject(new Error("call your model here")),
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const { pageCount, scannedPages } = await readPdfWithVision(new Uint8Array(readFileSync("report.pdf")), reader);
|
|
30
|
+
console.log(`pages: ${pageCount}, scanned: ${scannedPages ?? 0}`);
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## What it does
|
|
34
|
+
|
|
35
|
+
- **Which pages go.** Every page of a scan (a PDF with no text at all, or with an invisible OCR layer, which is never
|
|
36
|
+
trusted), else only the pages with no text; every page with `shouldReadAllPages`.
|
|
37
|
+
- **Batches.** At most 10 pages per call, and at most 12 MB per batch PDF (`OCR_BATCH_MAX_BYTES`): a larger batch is
|
|
38
|
+
halved until it fits, page order kept. The pages are written as a new PDF by pdf-skryba's own writer
|
|
39
|
+
(`copyPdfPages`): decrypted, through the reader's bounds, no third-party PDF library.
|
|
40
|
+
- **A reading that cannot be trusted fails as a whole.** A confidence outside [0.6, 1], an empty text, or a wrong
|
|
41
|
+
number of pages: `ReaderError` `OCR_LOW_CONFIDENCE`, never a partial document. What your model threw is not repeated:
|
|
42
|
+
`UNKNOWN`, with your error as `cause`.
|
|
43
|
+
- **Paragraphs.** A transcription has no structure but its blank lines: each blank line starts a paragraph.
|
|
44
|
+
|
|
45
|
+
## API
|
|
46
|
+
|
|
47
|
+
- `readPdfWithVision(bytes, reader, options?)` — the whole document, the same result as pdf-skryba's `extractPdf`.
|
|
48
|
+
Options: pdf-skryba's (`pageLanguage`, `limits`, `labels`, `shouldReturnScansAsImages`), plus `shouldReadAllPages`
|
|
49
|
+
and `languages` (handed to your reader).
|
|
50
|
+
- `readScannedPages(bytes, pageIndices, reader, options?)` — the transcribed blocks of some pages, by page index.
|
|
51
|
+
- `textToParagraphs(text)` — a transcription as paragraphs.
|
|
52
|
+
- `OCR_BATCH_MAX_BYTES` — the batch size bound.
|
|
53
|
+
- Types: `PdfVisionOptions`, `PageTextReader`, `PageText`, `PdfReading`.
|
|
54
|
+
|
|
55
|
+
## Versioning
|
|
56
|
+
|
|
57
|
+
The package follows [Semantic Versioning](https://semver.org): while it is `0.x`, a minor version may break the
|
|
58
|
+
published surface, and a patch never does. Each release is described in `CHANGELOG.md`.
|
|
59
|
+
|
|
60
|
+
## Contributing and security
|
|
61
|
+
|
|
62
|
+
See `CONTRIBUTING.md` and `SECURITY.md` in the [repository](https://github.com/numiastowski-design/pdf-vizyr). A
|
|
63
|
+
contribution is received under the MIT licence of the repository. Author: Miksumia.
|
|
64
|
+
|
|
65
|
+
## Licence
|
|
66
|
+
|
|
67
|
+
MIT (`LICENSE`). The test documents of the repository are not under the MIT licence: each keeps its own, written in
|
|
68
|
+
`fixtures/SOURCES.md`.
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// src/read.ts
|
|
2
|
+
import { ReaderError } from "doc-ir";
|
|
3
|
+
import {
|
|
4
|
+
composePdfReading,
|
|
5
|
+
copyPdfPages,
|
|
6
|
+
planPdfReading,
|
|
7
|
+
readPdfPages
|
|
8
|
+
} from "pdf-skryba/pages";
|
|
9
|
+
var BATCH_SIZE = 10;
|
|
10
|
+
var LOW_CONFIDENCE_THRESHOLD = 0.6;
|
|
11
|
+
var OCR_BATCH_MAX_BYTES = 12e6;
|
|
12
|
+
var textToParagraphs = (text) => text.split(/\n{2,}/).map(
|
|
13
|
+
(paragraph) => paragraph.split("\n").map((line) => line.trim()).filter((line) => line.length > 0).join(" ")
|
|
14
|
+
).filter((paragraph) => paragraph.length > 0).map((paragraph) => ({ kind: "paragraph", inlines: [{ text: paragraph }] }));
|
|
15
|
+
var groupsOf = (pages, size) => {
|
|
16
|
+
const groups = [];
|
|
17
|
+
for (let start = 0; start < pages.length; start += size) groups.push(pages.slice(start, start + size));
|
|
18
|
+
return groups;
|
|
19
|
+
};
|
|
20
|
+
var boundedBatches = (bytes, pages, maxBytes) => {
|
|
21
|
+
const batch = copyPdfPages(bytes, pages);
|
|
22
|
+
if (batch.length <= maxBytes || pages.length === 1) return [{ pages, bytes: batch }];
|
|
23
|
+
const half = Math.ceil(pages.length / 2);
|
|
24
|
+
return [
|
|
25
|
+
...boundedBatches(bytes, pages.slice(0, half), maxBytes),
|
|
26
|
+
...boundedBatches(bytes, pages.slice(half), maxBytes)
|
|
27
|
+
];
|
|
28
|
+
};
|
|
29
|
+
var planBatches = (bytes, pageIndices, maxBytes = OCR_BATCH_MAX_BYTES) => groupsOf(pageIndices, BATCH_SIZE).flatMap((group) => boundedBatches(bytes, group, maxBytes));
|
|
30
|
+
var readScannedPages = async (bytes, pageIndices, reader, opts) => {
|
|
31
|
+
const results = /* @__PURE__ */ new Map();
|
|
32
|
+
const readerOpts = opts?.languages ? { languages: [...opts.languages] } : void 0;
|
|
33
|
+
for (const { pages, bytes: batch } of planBatches(bytes, pageIndices)) {
|
|
34
|
+
const texts = await reader.readPages({ bytes: batch, mimeType: "application/pdf" }, readerOpts);
|
|
35
|
+
if (texts.length !== pages.length)
|
|
36
|
+
throw new ReaderError(
|
|
37
|
+
"OCR_LOW_CONFIDENCE",
|
|
38
|
+
`vision returned ${texts.length} page results for a ${pages.length}-page batch`
|
|
39
|
+
);
|
|
40
|
+
pages.forEach((pageIndex, index) => {
|
|
41
|
+
const text = texts[index];
|
|
42
|
+
const trusted = text !== void 0 && text.confidence >= LOW_CONFIDENCE_THRESHOLD && text.confidence <= 1;
|
|
43
|
+
if (!trusted || text.text.trim().length === 0)
|
|
44
|
+
throw new ReaderError(
|
|
45
|
+
"OCR_LOW_CONFIDENCE",
|
|
46
|
+
`page ${pageIndex}: confidence=${text?.confidence ?? "n/a"}, textLength=${text?.text.length ?? 0}`
|
|
47
|
+
);
|
|
48
|
+
results.set(pageIndex, textToParagraphs(text.text));
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return results;
|
|
52
|
+
};
|
|
53
|
+
var readingFailure = (error, counts) => error instanceof ReaderError ? new ReaderError(error.code, error.message, counts) : new ReaderError("UNKNOWN", "the AI reading failed", counts, { cause: error });
|
|
54
|
+
var readPdfWithVision = async (bytes, reader, opts) => {
|
|
55
|
+
const reading = await readPdfPages(bytes, opts);
|
|
56
|
+
const plan = planPdfReading(reading, opts?.shouldReadAllPages === true);
|
|
57
|
+
if (plan.toRead.length === 0) return composePdfReading(reading, plan, opts);
|
|
58
|
+
const transcribed = await readScannedPages(bytes, plan.toRead, reader, opts).catch((error) => {
|
|
59
|
+
throw readingFailure(error, { pageCount: reading.pages.length, scannedPageCount: plan.scannedPages });
|
|
60
|
+
});
|
|
61
|
+
return composePdfReading(reading, plan, opts, transcribed);
|
|
62
|
+
};
|
|
63
|
+
export {
|
|
64
|
+
OCR_BATCH_MAX_BYTES,
|
|
65
|
+
readPdfWithVision,
|
|
66
|
+
readScannedPages,
|
|
67
|
+
textToParagraphs
|
|
68
|
+
};
|
|
69
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/read.ts"],
|
|
4
|
+
"sourcesContent": ["/** The AI reading of a PDF's scanned pages: the pages with no digital text sent to a page-text reader in batches, its\n * transcriptions checked, and the document composed again with them, in page order.\n * Decides: which pages go (`pdf-skryba`'s plan: every page of a scan, or every page when asked, else the pages with no\n * text); the batches (at most `BATCH_SIZE` pages, each batch PDF at most `OCR_BATCH_MAX_BYTES`, halved until it fits);\n * the gate a transcription must pass (a confidence in [`LOW_CONFIDENCE_THRESHOLD`, 1] and some text, else the WHOLE\n * reading fails, `OCR_LOW_CONFIDENCE`); how a transcription becomes paragraphs (a blank line is the only break).\n * NOT here: reading the PDF and composing its document (`pdf-skryba`, its `pages` entry), slicing the pages\n * (`pdf-skryba`'s `copyPdfPages`, our own writer, through its reader's bounds), the model (the caller's reader). */\n\nimport { ReaderError, type IRBlock, type PageTextReader } from \"doc-ir\";\nimport {\n composePdfReading,\n copyPdfPages,\n planPdfReading,\n readPdfPages,\n type ExtractOptions,\n type PdfReading,\n} from \"pdf-skryba/pages\";\n\n/** Pages per call to the reader, not one call per page: a document with a handful of scanned pages fits in one batch. */\nconst BATCH_SIZE = 10;\n\n/** A page read below this confidence fails the reading (`OCR_LOW_CONFIDENCE`): no page is published nearly empty.\n * Starting value to calibrate. */\nconst LOW_CONFIDENCE_THRESHOLD = 0.6;\n\n/** \uD83D\uDD34 SECURITY BOUND: the largest size of one batch PDF sent to the reader, kept below the usual model services'\n * limits (base64 inflates the payload by a third). A single page above it still goes alone. Starting value to\n * calibrate. */\nexport const OCR_BATCH_MAX_BYTES = 12_000_000;\n\nexport interface PdfVisionOptions extends ExtractOptions {\n /** Send every page, not only the pages with no text: the reader's transcription replaces the text layer. */\n readonly shouldReadAllPages?: boolean;\n /** The languages the reader may use, when the caller knows them. */\n readonly languages?: readonly string[];\n}\n\n/** A transcription's paragraphs: it has no structure but its blank lines, the only break a reader keeps consistently. */\nexport const textToParagraphs = (text: string): IRBlock[] =>\n text\n .split(/\\n{2,}/)\n .map((paragraph) =>\n paragraph\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .join(\" \"),\n )\n .filter((paragraph) => paragraph.length > 0)\n .map((paragraph) => ({ kind: \"paragraph\" as const, inlines: [{ text: paragraph }] }));\n\n/** The pages split in groups of at most `size`, in order. */\nconst groupsOf = (pages: readonly number[], size: number): number[][] => {\n const groups: number[][] = [];\n for (let start = 0; start < pages.length; start += size) groups.push(pages.slice(start, start + size));\n return groups;\n};\n\n/** The batch PDF of `pages`, halved recursively while it passes `OCR_BATCH_MAX_BYTES` with more than one page; the\n * batches come out in page order. */\nconst boundedBatches = (\n bytes: Uint8Array,\n pages: number[],\n maxBytes: number,\n): { pages: number[]; bytes: Uint8Array }[] => {\n const batch = copyPdfPages(bytes, pages);\n if (batch.length <= maxBytes || pages.length === 1) return [{ pages, bytes: batch }];\n const half = Math.ceil(pages.length / 2);\n return [\n ...boundedBatches(bytes, pages.slice(0, half), maxBytes),\n ...boundedBatches(bytes, pages.slice(half), maxBytes),\n ];\n};\n\n/** Every batch of `pageIndices`, in page order: groups of `BATCH_SIZE`, each halved while above `maxBytes`. Exported\n * for the tests, which pass a smaller bound than `OCR_BATCH_MAX_BYTES` on real documents. */\nexport const planBatches = (\n bytes: Uint8Array,\n pageIndices: readonly number[],\n maxBytes = OCR_BATCH_MAX_BYTES,\n): { pages: number[]; bytes: Uint8Array }[] =>\n groupsOf(pageIndices, BATCH_SIZE).flatMap((group) => boundedBatches(bytes, group, maxBytes));\n\n/** Every page of `pageIndices` (0-based) read by `reader`, as blocks keyed by that index. Throws\n * `ReaderError(\"OCR_LOW_CONFIDENCE\")` \u2014 the whole call, not the page \u2014 when a batch's count is wrong or a page fails\n * the gate: an unreadable scan fails loudly, never as a partial document. NO FALLBACK on an invisible OCR layer. */\nexport const readScannedPages = async (\n bytes: Uint8Array,\n pageIndices: readonly number[],\n reader: PageTextReader,\n opts?: { readonly languages?: readonly string[] },\n): Promise<Map<number, IRBlock[]>> => {\n const results = new Map<number, IRBlock[]>();\n const readerOpts = opts?.languages ? { languages: [...opts.languages] } : undefined;\n // Every batch built before any call, so the source is not held while the reader works.\n for (const { pages, bytes: batch } of planBatches(bytes, pageIndices)) {\n const texts = await reader.readPages({ bytes: batch, mimeType: \"application/pdf\" }, readerOpts);\n if (texts.length !== pages.length)\n throw new ReaderError(\n \"OCR_LOW_CONFIDENCE\",\n `vision returned ${texts.length} page results for a ${pages.length}-page batch`,\n );\n pages.forEach((pageIndex, index) => {\n const text = texts[index];\n // IN RANGE, not merely \u00AB not below the floor \u00BB: NaN and any confidence above 1 are refused too.\n const trusted = text !== undefined && text.confidence >= LOW_CONFIDENCE_THRESHOLD && text.confidence <= 1;\n if (!trusted || text.text.trim().length === 0)\n throw new ReaderError(\n \"OCR_LOW_CONFIDENCE\",\n `page ${pageIndex}: confidence=${text?.confidence ?? \"n/a\"}, textLength=${text?.text.length ?? 0}`,\n );\n results.set(pageIndex, textToParagraphs(text.text));\n });\n }\n return results;\n};\n\n/** The error a failed reading becomes: its own code kept, the file's counts carried; another error rides as `cause`\n * (what the model service threw is not ours to repeat). */\nconst readingFailure = (error: unknown, counts: { pageCount: number; scannedPageCount: number }): ReaderError =>\n error instanceof ReaderError\n ? new ReaderError(error.code, error.message, counts)\n : new ReaderError(\"UNKNOWN\", \"the AI reading failed\", counts, { cause: error });\n\n/** A PDF read whole, its scanned pages (or every page, `shouldReadAllPages`) transcribed by `reader`, the document\n * composed in page order: one tab per page, digital or transcribed alike. Same result shape as `pdf-skryba`'s\n * `extractPdf`. */\nexport const readPdfWithVision = async (\n bytes: Uint8Array,\n reader: PageTextReader,\n opts?: PdfVisionOptions,\n): Promise<PdfReading> => {\n const reading = await readPdfPages(bytes, opts);\n const plan = planPdfReading(reading, opts?.shouldReadAllPages === true);\n if (plan.toRead.length === 0) return composePdfReading(reading, plan, opts);\n const transcribed = await readScannedPages(bytes, plan.toRead, reader, opts).catch((error: unknown) => {\n throw readingFailure(error, { pageCount: reading.pages.length, scannedPageCount: plan.scannedPages });\n });\n return composePdfReading(reading, plan, opts, transcribed);\n};\n"],
|
|
5
|
+
"mappings": ";AASA,SAAS,mBAAsD;AAC/D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAGP,IAAM,aAAa;AAInB,IAAM,2BAA2B;AAK1B,IAAM,sBAAsB;AAU5B,IAAM,mBAAmB,CAAC,SAC/B,KACG,MAAM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
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ReaderError as i}from"doc-ir";import{composePdfReading as p,copyPdfPages as y,planPdfReading as R,readPdfPages as b}from"pdf-skryba/pages";var x=10,O=.6,u=12e6,f=n=>n.split(/\n{2,}/).map(e=>e.split(`
|
|
2
|
+
`).map(t=>t.trim()).filter(t=>t.length>0).join(" ")).filter(e=>e.length>0).map(e=>({kind:"paragraph",inlines:[{text:e}]})),C=(n,e)=>{let t=[];for(let a=0;a<n.length;a+=e)t.push(n.slice(a,a+e));return t},g=(n,e,t)=>{let a=y(n,e);if(a.length<=t||e.length===1)return[{pages:e,bytes:a}];let r=Math.ceil(e.length/2);return[...g(n,e.slice(0,r),t),...g(n,e.slice(r),t)]},E=(n,e,t=u)=>C(e,x).flatMap(a=>g(n,a,t)),h=async(n,e,t,a)=>{let r=new Map,d=a?.languages?{languages:[...a.languages]}:void 0;for(let{pages:s,bytes:P}of E(n,e)){let c=await t.readPages({bytes:P,mimeType:"application/pdf"},d);if(c.length!==s.length)throw new i("OCR_LOW_CONFIDENCE",`vision returned ${c.length} page results for a ${s.length}-page batch`);s.forEach((l,m)=>{let o=c[m];if(!(o!==void 0&&o.confidence>=O&&o.confidence<=1)||o.text.trim().length===0)throw new i("OCR_LOW_CONFIDENCE",`page ${l}: confidence=${o?.confidence??"n/a"}, textLength=${o?.text.length??0}`);r.set(l,f(o.text))})}return r},_=(n,e)=>n instanceof i?new i(n.code,n.message,e):new i("UNKNOWN","the AI reading failed",e,{cause:n}),A=async(n,e,t)=>{let a=await b(n,t),r=R(a,t?.shouldReadAllPages===!0);if(r.toRead.length===0)return p(a,r,t);let d=await h(n,r.toRead,e,t).catch(s=>{throw _(s,{pageCount:a.pages.length,scannedPageCount:r.scannedPages})});return p(a,r,t,d)};export{u as OCR_BATCH_MAX_BYTES,A as readPdfWithVision,h as readScannedPages,f as textToParagraphs};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type IRBlock, type PageTextReader } from "doc-ir";
|
|
2
|
+
import { type ExtractOptions, type PdfReading } from "pdf-skryba/pages";
|
|
3
|
+
export declare const OCR_BATCH_MAX_BYTES = 12000000;
|
|
4
|
+
export interface PdfVisionOptions extends ExtractOptions {
|
|
5
|
+
readonly shouldReadAllPages?: boolean;
|
|
6
|
+
readonly languages?: readonly string[];
|
|
7
|
+
}
|
|
8
|
+
export declare const textToParagraphs: (text: string) => IRBlock[];
|
|
9
|
+
export declare const planBatches: (bytes: Uint8Array, pageIndices: readonly number[], maxBytes?: number) => {
|
|
10
|
+
pages: number[];
|
|
11
|
+
bytes: Uint8Array;
|
|
12
|
+
}[];
|
|
13
|
+
export declare const readScannedPages: (bytes: Uint8Array, pageIndices: readonly number[], reader: PageTextReader, opts?: {
|
|
14
|
+
readonly languages?: readonly string[];
|
|
15
|
+
}) => Promise<Map<number, IRBlock[]>>;
|
|
16
|
+
export declare const readPdfWithVision: (bytes: Uint8Array, reader: PageTextReader, opts?: PdfVisionOptions) => Promise<PdfReading>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,78 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pdf-vizyr",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Reads a PDF's scanned pages with an AI model of your own: batches of pages sliced by our own PDF writer, transcriptions checked, the document composed in page order on pdf-skryba.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pdf",
|
|
7
|
+
"ocr",
|
|
8
|
+
"scanned-pdf",
|
|
9
|
+
"vision",
|
|
10
|
+
"page-text",
|
|
11
|
+
"document-parser"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": "Miksumia <contact@miksumia.com>",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/numiastowski-design/pdf-vizyr.git"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/numiastowski-design/pdf-vizyr#readme",
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/numiastowski-design/pdf-vizyr/issues"
|
|
22
|
+
},
|
|
23
|
+
"type": "module",
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=24"
|
|
26
|
+
},
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/types/index.d.ts",
|
|
30
|
+
"default": "./dist/index.js"
|
|
31
|
+
},
|
|
32
|
+
"./min": {
|
|
33
|
+
"types": "./dist/types/index.d.ts",
|
|
34
|
+
"default": "./dist/index.min.js"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"sideEffects": false,
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsx scripts/build.ts",
|
|
40
|
+
"test": "vitest run",
|
|
41
|
+
"lint": "eslint --max-warnings 0 src scripts",
|
|
42
|
+
"format:check": "prettier --check src scripts",
|
|
43
|
+
"typecheck": "node node_modules/typescript/bin/tsc --noEmit && node node_modules/typescript7/bin/tsc --noEmit",
|
|
44
|
+
"lint:pack": "publint run --strict && attw --pack . --profile esm-only",
|
|
45
|
+
"prepack": "npm run build"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"files": [
|
|
51
|
+
"dist",
|
|
52
|
+
"README.md",
|
|
53
|
+
"CHANGELOG.md",
|
|
54
|
+
"LICENSE"
|
|
55
|
+
],
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@arethetypeswrong/cli": "0.18.5",
|
|
58
|
+
"@types/node": "26.6.11",
|
|
59
|
+
"esbuild": "0.28.2",
|
|
60
|
+
"eslint": "10.16.0",
|
|
61
|
+
"eslint-plugin-sonarjs": "4.2.3",
|
|
62
|
+
"fast-check": "4.11.0",
|
|
63
|
+
"prettier": "3.10.1",
|
|
64
|
+
"publint": "0.3.25",
|
|
65
|
+
"tsx": "4.23.15",
|
|
66
|
+
"typescript": "6.0.3",
|
|
67
|
+
"typescript-eslint": "8.74.0",
|
|
68
|
+
"typescript7": "npm:typescript@7.0.2",
|
|
69
|
+
"vitest": "5.1.2"
|
|
70
|
+
},
|
|
71
|
+
"allowScripts": {
|
|
72
|
+
"esbuild": false
|
|
73
|
+
},
|
|
74
|
+
"dependencies": {
|
|
75
|
+
"doc-ir": "0.4.1",
|
|
76
|
+
"pdf-skryba": "^3.0.0"
|
|
77
|
+
}
|
|
78
|
+
}
|