@arkyc/ocr 2.0.0 → 2.1.1
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/dist/checks.d.mts +5 -7
- package/dist/checks.d.mts.map +1 -1
- package/dist/drivers/ai.d.mts +16 -14
- package/dist/drivers/ai.d.mts.map +1 -1
- package/dist/drivers/ai.mjs +29 -12
- package/dist/drivers/ai.mjs.map +1 -1
- package/dist/drivers/external.d.mts +1 -3
- package/dist/drivers/external.d.mts.map +1 -1
- package/dist/drivers/mock.d.mts +1 -3
- package/dist/drivers/mock.d.mts.map +1 -1
- package/dist/drivers/preprocess.d.mts +6 -6
- package/dist/drivers/preprocess.d.mts.map +1 -1
- package/dist/drivers/preprocess.mjs.map +1 -1
- package/dist/drivers/tesseract.d.mts +4 -6
- package/dist/drivers/tesseract.d.mts.map +1 -1
- package/dist/parsers/generic.d.mts +1 -3
- package/dist/parsers/generic.d.mts.map +1 -1
- package/dist/parsers/mrz.d.mts +1 -3
- package/dist/parsers/mrz.d.mts.map +1 -1
- package/dist/parsers/registry.d.mts +3 -5
- package/dist/parsers/registry.d.mts.map +1 -1
- package/dist/parsers/types.d.mts +3 -5
- package/dist/parsers/types.d.mts.map +1 -1
- package/dist/registry.d.mts +1 -3
- package/dist/registry.d.mts.map +1 -1
- package/dist/types.d.mts +4 -6
- package/dist/types.d.mts.map +1 -1
- package/package.json +2 -2
package/dist/checks.d.mts
CHANGED
|
@@ -1,15 +1,14 @@
|
|
|
1
1
|
import { OcrFields } from "@arkyc/types";
|
|
2
|
-
|
|
3
2
|
//#region src/checks.d.ts
|
|
4
3
|
/** A deterministic inconsistency found on a document. */
|
|
5
|
-
type DocumentIssueCode = 'mrz_check_digit' | 'mrz_visual_mismatch' | 'issue_after_expiry' | 'birth_after_issue' | 'birth_in_future' | 'implausible_age';
|
|
6
|
-
interface DocumentIssue {
|
|
4
|
+
export type DocumentIssueCode = 'mrz_check_digit' | 'mrz_visual_mismatch' | 'issue_after_expiry' | 'birth_after_issue' | 'birth_in_future' | 'implausible_age';
|
|
5
|
+
export interface DocumentIssue {
|
|
7
6
|
code: DocumentIssueCode;
|
|
8
7
|
/** The fields involved. */
|
|
9
8
|
fields: string[];
|
|
10
9
|
}
|
|
11
10
|
/** The parts of an OCR result the checks read. */
|
|
12
|
-
interface DocumentCheckInput {
|
|
11
|
+
export interface DocumentCheckInput {
|
|
13
12
|
fields: OcrFields;
|
|
14
13
|
/** The driver's raw payload; MRZ check results and visual-zone fields live here. */
|
|
15
14
|
raw?: unknown;
|
|
@@ -19,7 +18,7 @@ interface DocumentCheckInput {
|
|
|
19
18
|
* Deterministic document checks: MRZ check digits, MRZ against the visual zone,
|
|
20
19
|
* and dates that cannot happen.
|
|
21
20
|
*/
|
|
22
|
-
declare class DocumentChecks {
|
|
21
|
+
export declare class DocumentChecks {
|
|
23
22
|
/**
|
|
24
23
|
* Every issue found on the document. An empty list means nothing was provably wrong.
|
|
25
24
|
*
|
|
@@ -39,7 +38,6 @@ declare class DocumentChecks {
|
|
|
39
38
|
* @param on
|
|
40
39
|
* @returns
|
|
41
40
|
*/
|
|
42
|
-
declare function ageOn(dateOfBirth: string, on?: Date): number | null;
|
|
41
|
+
export declare function ageOn(dateOfBirth: string, on?: Date): number | null;
|
|
43
42
|
//#endregion
|
|
44
|
-
export { DocumentCheckInput, DocumentChecks, DocumentIssue, DocumentIssueCode, ageOn };
|
|
45
43
|
//# sourceMappingURL=checks.d.mts.map
|
package/dist/checks.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checks.d.mts","names":[],"sources":["../src/checks.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"checks.d.mts","names":[],"sources":["../src/checks.ts"],"mappings":";;;YAGY;iBAQK;EACf,MAAM;;EAEN;;;iBAIe;EACf,QAAQ;;EAER;EACA,MAAM;;;;;;qBAeK;;;;;;;SAOJ,QAAQ,OAAO,qBAAqB;iBAI5B;iBAwBA;;iBAsBA;;;;;;;;;wBAqBD,MAAM,qBAAqB,KAAI"}
|
package/dist/drivers/ai.d.mts
CHANGED
|
@@ -1,19 +1,18 @@
|
|
|
1
1
|
import { OcrDriver, OcrRequest } from "../types.mjs";
|
|
2
2
|
import { DocumentType, OcrAuthenticity, OcrFields, OcrResultData } from "@arkyc/types";
|
|
3
|
-
|
|
4
3
|
//#region src/drivers/ai.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* A small, cheap vision model is plenty for reading printed/MRZ document text.
|
|
7
6
|
*/
|
|
8
|
-
declare const DEFAULT_AI_MODEL = "claude-haiku-4-5-20251001";
|
|
7
|
+
export declare const DEFAULT_AI_MODEL = "claude-haiku-4-5-20251001";
|
|
9
8
|
/**
|
|
10
9
|
* Default Cloudflare Workers AI model: Gemma 4 accepts image input and tool calls.
|
|
11
10
|
*/
|
|
12
|
-
declare const DEFAULT_WORKERS_AI_MODEL = "@cf/google/gemma-4-26b-a4b-it";
|
|
11
|
+
export declare const DEFAULT_WORKERS_AI_MODEL = "@cf/google/gemma-4-26b-a4b-it";
|
|
13
12
|
/**
|
|
14
13
|
* Which hosted vision API backs the `ai` driver.
|
|
15
14
|
*/
|
|
16
|
-
type AiOcrProvider = 'anthropic' | 'workers-ai';
|
|
15
|
+
export type AiOcrProvider = 'anthropic' | 'workers-ai';
|
|
17
16
|
/**
|
|
18
17
|
* A base64 image ready for the messages API, with its detected media type.
|
|
19
18
|
*/
|
|
@@ -24,21 +23,23 @@ interface PreparedImage {
|
|
|
24
23
|
/**
|
|
25
24
|
* Raw fields the vision model returned, before validation/scoring.
|
|
26
25
|
*/
|
|
27
|
-
interface AiExtraction {
|
|
26
|
+
export interface AiExtraction {
|
|
28
27
|
fields: OcrFields;
|
|
29
28
|
/** The model's own legibility self-assessment in [0, 1], if it gave one. */
|
|
30
29
|
legibility?: number;
|
|
31
30
|
documentType?: DocumentType | null;
|
|
32
31
|
/** Best-effort tamper/replay read; omitted when the model reported nothing. */
|
|
33
32
|
authenticity?: OcrAuthenticity;
|
|
33
|
+
/** The model's own tool-call arguments, kept for debugging what it actually returned. */
|
|
34
|
+
modelOutput?: Record<string, unknown>;
|
|
34
35
|
}
|
|
35
36
|
/**
|
|
36
37
|
* Calls a vision model and returns the raw extracted fields. Injected so the
|
|
37
38
|
* driver's scoring can be unit-tested without a network call; the default
|
|
38
39
|
* implementation talks to the Anthropic messages API.
|
|
39
40
|
*/
|
|
40
|
-
type AiVisionExtract = (request: OcrRequest, images: PreparedImage[]) => Promise<AiExtraction>;
|
|
41
|
-
interface AnthropicOcrOptions {
|
|
41
|
+
export type AiVisionExtract = (request: OcrRequest, images: PreparedImage[]) => Promise<AiExtraction>;
|
|
42
|
+
export interface AnthropicOcrOptions {
|
|
42
43
|
/** Vision backend; defaults to `anthropic`. */
|
|
43
44
|
provider?: AiOcrProvider;
|
|
44
45
|
/** Anthropic API key, or the Cloudflare API token for `workers-ai`. */
|
|
@@ -79,7 +80,7 @@ interface AnthropicOcrOptions {
|
|
|
79
80
|
* {@link applyAuthenticity}) so a suspicious document routes to manual review —
|
|
80
81
|
* an LLM's authenticity guess never auto-rejects a user on its own.
|
|
81
82
|
*/
|
|
82
|
-
declare class AnthropicOcrDriver implements OcrDriver {
|
|
83
|
+
export declare class AnthropicOcrDriver implements OcrDriver {
|
|
83
84
|
readonly name = "ai";
|
|
84
85
|
private readonly provider;
|
|
85
86
|
private readonly model;
|
|
@@ -105,7 +106,7 @@ declare class AnthropicOcrDriver implements OcrDriver {
|
|
|
105
106
|
* @param legibility
|
|
106
107
|
* @returns
|
|
107
108
|
*/
|
|
108
|
-
declare function scoreConfidence(fields: OcrFields, legibility?: number): number;
|
|
109
|
+
export declare function scoreConfidence(fields: OcrFields, legibility?: number): number;
|
|
109
110
|
/**
|
|
110
111
|
* Fold the authenticity read into the field-derived confidence. Only ever lowers
|
|
111
112
|
* the score, and only when a concrete flag fired — a genuine (or unassessed)
|
|
@@ -118,14 +119,14 @@ declare function scoreConfidence(fields: OcrFields, legibility?: number): number
|
|
|
118
119
|
* @param authenticity
|
|
119
120
|
* @returns
|
|
120
121
|
*/
|
|
121
|
-
declare function applyAuthenticity(fieldScore: number, authenticity?: OcrAuthenticity): number;
|
|
122
|
+
export declare function applyAuthenticity(fieldScore: number, authenticity?: OcrAuthenticity): number;
|
|
122
123
|
/**
|
|
123
124
|
* Build the default vision call against the Anthropic messages API.
|
|
124
125
|
*
|
|
125
126
|
* @param input
|
|
126
127
|
* @returns
|
|
127
128
|
*/
|
|
128
|
-
declare function anthropicVision(opts: {
|
|
129
|
+
export declare function anthropicVision(opts: {
|
|
129
130
|
apiKey: string;
|
|
130
131
|
model: string;
|
|
131
132
|
baseUrl: string;
|
|
@@ -141,13 +142,14 @@ declare function anthropicVision(opts: {
|
|
|
141
142
|
* @param opts
|
|
142
143
|
* @returns
|
|
143
144
|
*/
|
|
144
|
-
declare function workersAiVision(opts: {
|
|
145
|
+
export declare function workersAiVision(opts: {
|
|
145
146
|
apiKey: string;
|
|
146
|
-
model: string;
|
|
147
|
+
model: string;
|
|
148
|
+
/** OpenAI-compatible base ending in `/v1`. */
|
|
147
149
|
baseUrl: string;
|
|
148
150
|
timeoutMs?: number;
|
|
149
151
|
maxRetries?: number;
|
|
150
152
|
}): AiVisionExtract;
|
|
151
153
|
//#endregion
|
|
152
|
-
export {
|
|
154
|
+
export {};
|
|
153
155
|
//# sourceMappingURL=ai.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai.d.mts","names":[],"sources":["../../src/drivers/ai.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"ai.d.mts","names":[],"sources":["../../src/drivers/ai.ts"],"mappings":";;;;;;qBAaa;;;;qBAKA;;;;YAKD;;;;UAsBF;EACR;EACA;;;;;iBAMe;EACf,QAAQ;;EAER;EACA,eAAe;;EAEf,eAAe;;EAEf,cAAc;;;;;;;YAQJ,mBAAmB,SAAS,YAAY,QAAQ,oBAAoB,QAAQ;iBAEvE;;EAEf,WAAW;;EAEX;;EAEA;;EAEA;;;;;;EAMA;;EAEA;;EAEA;;EAEA;;EAEA,UAAU;;;;;;;;;;;;;;;;;;;qBAoBC,8BAA8B;WAChC;mBAEQ;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS;EAoCf,QAAQ,SAAS,aAAa,QAAQ;;;;;;;UA6B9B;;;;;;;;;;;;wBAyCA,gBAAgB,QAAQ,WAAW;;;;;;;;;;;;;wBAiCnC,kBAAkB,oBAAoB,eAAe;;;;;;;wBAsKrD,gBAAgB;EAC9B;EACA;EACA;EACA;EACA;IACE;;;;;;;;;;wBA4FY,gBAAgB;EAC9B;EACA;;EAEA;EACA;EACA;IACE"}
|
package/dist/drivers/ai.mjs
CHANGED
|
@@ -89,7 +89,8 @@ var AnthropicOcrDriver = class {
|
|
|
89
89
|
model: this.model,
|
|
90
90
|
legibility: raw.legibility ?? null,
|
|
91
91
|
documentType: raw.documentType ?? request.documentType ?? null,
|
|
92
|
-
authenticity: authenticity ?? null
|
|
92
|
+
authenticity: authenticity ?? null,
|
|
93
|
+
modelOutput: raw.modelOutput ?? null
|
|
93
94
|
}
|
|
94
95
|
};
|
|
95
96
|
}
|
|
@@ -138,13 +139,15 @@ function normalizeFields(fields) {
|
|
|
138
139
|
* @returns
|
|
139
140
|
*/
|
|
140
141
|
function scoreConfidence(fields, legibility) {
|
|
141
|
-
|
|
142
|
+
const base = [
|
|
142
143
|
[present(fields.firstName) && present(fields.lastName) || present(fields.fullName), .28],
|
|
143
144
|
[isIsoDate(fields.dateOfBirth), .22],
|
|
144
145
|
[present(fields.documentNumber) && fields.documentNumber.trim().length >= 4, .22],
|
|
145
146
|
[isIsoDate(fields.expiryDate), .16],
|
|
146
147
|
[present(fields.nationality), .12]
|
|
147
|
-
].reduce((sum, [ok, weight]) => ok ? sum + weight : sum, 0)
|
|
148
|
+
].reduce((sum, [ok, weight]) => ok ? sum + weight : sum, 0);
|
|
149
|
+
const legible = clamp01(legibility ?? 1);
|
|
150
|
+
return clamp01(base * (.85 + .15 * legible));
|
|
148
151
|
}
|
|
149
152
|
/**
|
|
150
153
|
* Hard ceiling on OCR confidence once any authenticity flag fires. Below the
|
|
@@ -193,7 +196,7 @@ const READ_TOOL = {
|
|
|
193
196
|
},
|
|
194
197
|
documentNumber: {
|
|
195
198
|
type: "string",
|
|
196
|
-
description: "Document/serial number as printed."
|
|
199
|
+
description: "Document/serial number as printed; for a national ID card or slip, the national identification number (e.g. NIN)."
|
|
197
200
|
},
|
|
198
201
|
issueDate: {
|
|
199
202
|
type: "string",
|
|
@@ -437,17 +440,31 @@ function workersAiVision(opts) {
|
|
|
437
440
|
* @returns
|
|
438
441
|
*/
|
|
439
442
|
function mapToolInput(input) {
|
|
440
|
-
const str = (v) =>
|
|
443
|
+
const str = (v) => {
|
|
444
|
+
if (typeof v === "number" && Number.isFinite(v)) return String(v);
|
|
445
|
+
return typeof v === "string" && v.trim() ? v.trim() : void 0;
|
|
446
|
+
};
|
|
447
|
+
const source = {
|
|
448
|
+
...input.fields && typeof input.fields === "object" ? input.fields : {},
|
|
449
|
+
...input
|
|
450
|
+
};
|
|
451
|
+
const pick = (...keys) => {
|
|
452
|
+
for (const key of keys) {
|
|
453
|
+
const value = str(source[key]);
|
|
454
|
+
if (value) return value;
|
|
455
|
+
}
|
|
456
|
+
};
|
|
441
457
|
const docType = str(input.documentType);
|
|
442
458
|
return {
|
|
459
|
+
modelOutput: input,
|
|
443
460
|
fields: {
|
|
444
|
-
firstName:
|
|
445
|
-
lastName:
|
|
446
|
-
fullName:
|
|
447
|
-
dateOfBirth:
|
|
448
|
-
documentNumber:
|
|
449
|
-
expiryDate:
|
|
450
|
-
nationality:
|
|
461
|
+
firstName: pick("firstName", "first_name", "givenName", "givenNames", "given_names", "forename", "forenames"),
|
|
462
|
+
lastName: pick("lastName", "last_name", "surname", "familyName", "family_name"),
|
|
463
|
+
fullName: pick("fullName", "full_name", "name"),
|
|
464
|
+
dateOfBirth: pick("dateOfBirth", "date_of_birth", "dob", "birthDate", "birth_date"),
|
|
465
|
+
documentNumber: pick("documentNumber", "document_number", "idNumber", "id_number", "nin", "nationalIdNumber", "national_id_number", "number"),
|
|
466
|
+
expiryDate: pick("expiryDate", "expiry_date", "dateOfExpiry", "date_of_expiry", "expiry"),
|
|
467
|
+
nationality: pick("nationality")
|
|
451
468
|
},
|
|
452
469
|
legibility: typeof input.legibility === "number" ? input.legibility : void 0,
|
|
453
470
|
documentType: docType && DOCUMENT_TYPES.includes(docType) ? docType : null,
|
package/dist/drivers/ai.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai.mjs","names":[],"sources":["../../src/drivers/ai.ts"],"sourcesContent":["import type { DocumentType, OcrAuthenticity, OcrFields, OcrResultData } from '@arkyc/types'\nimport type { OcrDriver, OcrRequest } from '../types'\n\nconst clamp01 = (n: number): number => Math.min(1, Math.max(0, n))\n\n/**\n * Anthropic's default API base; override for a gateway/proxy.\n */\nconst DEFAULT_BASE_URL = 'https://api.anthropic.com'\n\n/**\n * A small, cheap vision model is plenty for reading printed/MRZ document text.\n */\nexport const DEFAULT_AI_MODEL = 'claude-haiku-4-5-20251001'\n\n/**\n * Default Cloudflare Workers AI model: Gemma 4 accepts image input and tool calls.\n */\nexport const DEFAULT_WORKERS_AI_MODEL = '@cf/google/gemma-4-26b-a4b-it'\n\n/**\n * Which hosted vision API backs the `ai` driver.\n */\nexport type AiOcrProvider = 'anthropic' | 'workers-ai'\n\n/**\n * Longest edge (px) we upload. The API downsamples anything larger anyway and\n * bills by the resampled size, so this is a cost/bandwidth bound, not a quality\n * one — small enough to be cheap, large enough to keep the MRZ legible.\n */\nconst DEFAULT_MAX_EDGE = 1568\n\n/**\n * Per-attempt request timeout (ms) — a hung connection must not stall a worker.\n */\nconst DEFAULT_TIMEOUT_MS = 30_000\n\n/**\n * Bounded in-driver retries on rate-limit/overload; the job queue retries beyond.\n */\nconst DEFAULT_MAX_RETRIES = 2\n\n/**\n * A base64 image ready for the messages API, with its detected media type.\n */\ninterface PreparedImage {\n mediaType: 'image/jpeg' | 'image/png' | 'image/webp'\n data: string\n}\n\n/**\n * Raw fields the vision model returned, before validation/scoring.\n */\nexport interface AiExtraction {\n fields: OcrFields\n /** The model's own legibility self-assessment in [0, 1], if it gave one. */\n legibility?: number\n documentType?: DocumentType | null\n /** Best-effort tamper/replay read; omitted when the model reported nothing. */\n authenticity?: OcrAuthenticity\n}\n\n/**\n * Calls a vision model and returns the raw extracted fields. Injected so the\n * driver's scoring can be unit-tested without a network call; the default\n * implementation talks to the Anthropic messages API.\n */\nexport type AiVisionExtract = (request: OcrRequest, images: PreparedImage[]) => Promise<AiExtraction>\n\nexport interface AnthropicOcrOptions {\n /** Vision backend; defaults to `anthropic`. */\n provider?: AiOcrProvider\n /** Anthropic API key, or the Cloudflare API token for `workers-ai`. */\n apiKey?: string\n /** Cloudflare account id; required for `workers-ai` unless `baseUrl` is set. */\n accountId?: string\n /** Model id; defaults to {@link DEFAULT_AI_MODEL} or {@link DEFAULT_WORKERS_AI_MODEL}. */\n model?: string\n /**\n * API base URL. Anthropic: defaults to {@link DEFAULT_BASE_URL}. Workers AI: the\n * OpenAI-compatible base ending in `/v1` (e.g. an AI Gateway URL), defaulting to\n * the account's `/ai/v1` endpoint.\n */\n baseUrl?: string\n /** Longest image edge (px) to upload; defaults to {@link DEFAULT_MAX_EDGE}. */\n maxEdge?: number\n /** Per-attempt request timeout (ms); defaults to {@link DEFAULT_TIMEOUT_MS}. */\n timeoutMs?: number\n /** Bounded retries on 429/529; defaults to {@link DEFAULT_MAX_RETRIES}. */\n maxRetries?: number\n /** Override the vision call (tests). When set, `apiKey` is not required. */\n extract?: AiVisionExtract\n}\n\n/**\n * AI OCR driver: hands the document image(s) to a vision LLM (Claude by default,\n * or a Cloudflare Workers AI model with `provider: 'workers-ai'`) and maps the structured response onto {@link OcrResultData}.\n *\n * Confidence is **not** taken from the model's self-report — LLMs are poorly\n * calibrated and will state high confidence on hallucinated fields. Instead it's\n * derived deterministically from which fields came back and whether they're\n * structurally valid (see {@link scoreConfidence}), so the value feeding the\n * decision engine's `ocrConfidenceThreshold` is meaningful. The model's own\n * legibility read is folded in only as a small soft penalty.\n *\n * It also asks the model for a best-effort, image-only authenticity read\n * (screen-replay, photocopy, digital/physical tampering). That signal is\n * advisory: a fired flag only *caps* the OCR confidence (see\n * {@link applyAuthenticity}) so a suspicious document routes to manual review —\n * an LLM's authenticity guess never auto-rejects a user on its own.\n */\nexport class AnthropicOcrDriver implements OcrDriver {\n readonly name = 'ai'\n\n private readonly provider: AiOcrProvider\n private readonly model: string\n private readonly maxEdge: number\n private readonly vision: AiVisionExtract\n\n constructor(options: AnthropicOcrOptions = {}) {\n this.provider = options.provider ?? 'anthropic'\n if (!options.apiKey && !options.extract) {\n throw new Error('AnthropicOcrDriver requires config.apiKey')\n }\n this.model = options.model ?? (this.provider === 'workers-ai' ? DEFAULT_WORKERS_AI_MODEL : DEFAULT_AI_MODEL)\n this.maxEdge = options.maxEdge ?? DEFAULT_MAX_EDGE\n\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES\n if (options.extract) {\n this.vision = options.extract\n } else if (this.provider === 'workers-ai') {\n if (!options.accountId && !options.baseUrl) {\n throw new Error('AnthropicOcrDriver (workers-ai) requires config.accountId')\n }\n this.vision = workersAiVision({\n apiKey: options.apiKey as string,\n model: this.model,\n baseUrl: (\n options.baseUrl ?? `https://api.cloudflare.com/client/v4/accounts/${options.accountId}/ai/v1`\n ).replace(/\\/$/, ''),\n timeoutMs,\n maxRetries,\n })\n } else {\n this.vision = anthropicVision({\n apiKey: options.apiKey as string,\n model: this.model,\n baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, ''),\n timeoutMs,\n maxRetries,\n })\n }\n }\n\n async extract(request: OcrRequest): Promise<OcrResultData> {\n const images = await this.prepareImages(request)\n const raw = await this.vision(request, images)\n const fields = normalizeFields(raw.fields)\n const authenticity = raw.authenticity\n const confidence = applyAuthenticity(scoreConfidence(fields, raw.legibility), authenticity)\n\n return {\n fields,\n confidence,\n ...(authenticity ? { authenticity } : {}),\n raw: {\n provider: 'ai',\n backend: this.provider,\n model: this.model,\n legibility: raw.legibility ?? null,\n documentType: raw.documentType ?? request.documentType ?? null,\n authenticity: authenticity ?? null,\n },\n }\n }\n\n /**\n * Resize (best-effort) and base64-encode the front + optional back images.\n *\n * @param input\n * @returns\n */\n private async prepareImages(request: OcrRequest): Promise<PreparedImage[]> {\n const sources = [request.image, request.backImage].filter((b): b is Uint8Array => !!b && b.length > 0)\n return Promise.all(sources.map((bytes) => prepareImage(bytes, this.maxEdge)))\n }\n}\n\nconst present = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0\nconst isIsoDate = (v: unknown): boolean => present(v) && /^\\d{4}-\\d{2}-\\d{2}$/.test(v) && !Number.isNaN(Date.parse(v))\n\n/**\n * Trim/blank-out the model's fields; drop anything empty so callers see `undefined`.\n *\n * @param input\n * @returns\n */\nfunction normalizeFields(fields: OcrFields): OcrFields {\n const out: OcrFields = {}\n const set = (key: keyof OcrFields, value: string | undefined) => {\n if (present(value)) out[key] = value.trim()\n }\n set('firstName', fields.firstName)\n set('lastName', fields.lastName)\n set('fullName', fields.fullName)\n set('dateOfBirth', fields.dateOfBirth)\n set('documentNumber', fields.documentNumber)\n set('expiryDate', fields.expiryDate)\n set('issueDate', fields.issueDate)\n set('nationality', fields.nationality)\n return out\n}\n\n/**\n * Deterministic confidence in [0, 1] from field completeness + structural\n * validity. Weights sum to 1.0 when every field is present and well-formed; the\n * model's self-reported legibility can only pull the score down by up to 15%, so\n * trustworthy structure dominates an unreliable self-assessment.\n *\n * @param fields\n * @param legibility\n * @returns\n */\nexport function scoreConfidence(fields: OcrFields, legibility?: number): number {\n const hasName = (present(fields.firstName) && present(fields.lastName)) || present(fields.fullName)\n const checks: Array<[boolean, number]> = [\n [hasName, 0.28],\n [isIsoDate(fields.dateOfBirth), 0.22],\n [present(fields.documentNumber) && fields.documentNumber!.trim().length >= 4, 0.22],\n [isIsoDate(fields.expiryDate), 0.16],\n [present(fields.nationality), 0.12],\n ]\n const base = checks.reduce((sum, [ok, weight]) => (ok ? sum + weight : sum), 0)\n const legible = clamp01(legibility ?? 1)\n return clamp01(base * (0.85 + 0.15 * legible))\n}\n\n/**\n * Hard ceiling on OCR confidence once any authenticity flag fires. Below the\n * default `ocrConfidenceThreshold` (0.8), so a flagged document routes to manual\n * review regardless of how cleanly its fields read.\n */\nconst SUSPECT_CONFIDENCE_CEILING = 0.5\n\n/**\n * Fold the authenticity read into the field-derived confidence. Only ever lowers\n * the score, and only when a concrete flag fired — a genuine (or unassessed)\n * document is returned untouched. A flagged document is capped at both the\n * model's own authenticity confidence and {@link SUSPECT_CONFIDENCE_CEILING},\n * which lands it in manual review rather than auto-approval. This is deliberately\n * conservative: the LLM's authenticity guess can demote, never reject outright.\n *\n * @param fieldScore\n * @param authenticity\n * @returns\n */\nexport function applyAuthenticity(fieldScore: number, authenticity?: OcrAuthenticity): number {\n if (!authenticity || authenticity.genuine) return fieldScore\n return Math.min(fieldScore, clamp01(authenticity.confidence), SUSPECT_CONFIDENCE_CEILING)\n}\n\nconst SYSTEM_PROMPT =\n 'You are an OCR engine for identity documents. Read the visible printed text and ' +\n 'the machine-readable zone (MRZ) if present, and return the fields exactly as ' +\n 'printed. Do not guess, infer, or correct values you cannot clearly read — omit a ' +\n 'field rather than fabricate it. Dates must be ISO 8601 (YYYY-MM-DD).\\n\\n' +\n 'Identity documents print BOTH a date of issue and a date of expiry — never ' +\n 'confuse them. `expiryDate` is only the expiry/expiration/\"valid until\"/\"date of ' +\n 'expiry\" value (in an MRZ, the second date field, not the first). `issueDate` is ' +\n 'the \"date of issue\"/\"issued\"/\"valid from\" value. The expiry is later than the ' +\n 'issue date. If a document shows only an issue date and no expiry, return the ' +\n 'issue date in `issueDate` and leave `expiryDate` empty — do not put the issue ' +\n 'date in `expiryDate`.\\n\\n' +\n 'ALSO assess document authenticity, to the best of your ability, from the image ' +\n 'alone — and report it. Be conservative: raise a flag only on a clear, visible ' +\n 'sign. A genuine document that was merely photographed imperfectly (blur, glare ' +\n 'on a glossy original, a shadow, a crop) must NOT be flagged. Set `screenReplay` ' +\n 'when the image looks like a photo of a screen — moiré or a visible pixel grid, ' +\n 'backlit glow, refresh banding, or a device bezel (a replay attack). Set ' +\n '`photocopy` when it looks like a photo or scan of a printout/photocopy rather ' +\n 'than the physical document — flat matte paper, halftone dot printing, no ' +\n 'security features or hologram. Set `digitalTampering` for signs of digital ' +\n 'editing — mismatched fonts or kerning, misaligned or recoloured text, smudged ' +\n 'or cloned regions, a pasted-in portrait, or altered dates. Set ' +\n '`physicalTampering` for a substituted photo, peeled or lifted laminate, or ' +\n 'scratched-out / overwritten fields. Give `authenticityConfidence` from 0 ' +\n '(clearly fake or replayed) to 1 (clearly an authentic original), and list brief ' +\n 'supporting notes in `authenticityObservations`. You read and assess the ' +\n 'document; you do not make the final accept/reject decision.'\n\nconst READ_TOOL = {\n name: 'read_document',\n description: 'Return the identity fields read from the document image(s).',\n input_schema: {\n type: 'object',\n properties: {\n firstName: { type: 'string', description: 'Given name(s) as printed.' },\n lastName: { type: 'string', description: 'Surname / family name as printed.' },\n fullName: { type: 'string', description: 'Full name if given/surname cannot be separated.' },\n dateOfBirth: { type: 'string', description: 'Date of birth, ISO 8601 YYYY-MM-DD.' },\n documentNumber: { type: 'string', description: 'Document/serial number as printed.' },\n issueDate: {\n type: 'string',\n description: 'Date of issue (\"issued\"/\"valid from\"/\"issue date\"), ISO 8601 YYYY-MM-DD. NOT the expiry.',\n },\n expiryDate: {\n type: 'string',\n description:\n 'Expiry date (\"date of expiry\"/\"valid until\"/\"expiry date\"), ISO 8601 YYYY-MM-DD. Must be the expiry, never the issue date; omit if the document shows no expiry.',\n },\n nationality: { type: 'string', description: 'ISO 3166-1 alpha-3 country code if determinable.' },\n documentType: {\n type: 'string',\n enum: ['passport', 'id_card', 'drivers_license', 'residence_permit'],\n },\n legibility: {\n type: 'number',\n description: 'How clearly the document text could be read, 0 (illegible) to 1 (crisp).',\n },\n screenReplay: {\n type: 'boolean',\n description: 'Looks like a photo of a screen (moiré, pixel grid, backlit glow, refresh banding, bezel).',\n },\n photocopy: {\n type: 'boolean',\n description: 'Looks like a photo/scan of a printout or photocopy rather than the physical document.',\n },\n digitalTampering: {\n type: 'boolean',\n description:\n 'Signs of digital editing: mismatched fonts, misaligned/recoloured text, cloned regions, edited photo/dates.',\n },\n physicalTampering: {\n type: 'boolean',\n description:\n 'Signs of physical tampering: substituted photo, peeled laminate, scratched-out/overwritten fields.',\n },\n authenticityConfidence: {\n type: 'number',\n description: 'Authenticity confidence, 0 (clearly fake/replayed) to 1 (clearly an authentic original).',\n },\n authenticityObservations: {\n type: 'array',\n items: { type: 'string' },\n description: 'Brief notes supporting any authenticity flag raised.',\n },\n },\n },\n} as const\n\n/**\n * Minimal shape of the messages-API response we read.\n *\n */\ninterface AnthropicResponse {\n content?: Array<{ type: string; name?: string; input?: Record<string, unknown> }>\n}\n\nconst DOCUMENT_TYPES: readonly DocumentType[] = ['passport', 'id_card', 'drivers_license', 'residence_permit']\n\n/**\n * HTTP statuses worth a bounded retry: rate-limited / overloaded / unavailable.\n */\nconst RETRYABLE_STATUS = new Set([429, 503, 529])\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))\n\n/**\n * Exponential backoff (ms) for attempt 0, 1, 2…, capped at 8s.\n */\nconst backoffMs = (attempt: number): number => Math.min(8_000, 500 * 2 ** attempt)\n\n/**\n * Parse a `retry-after` header (seconds) into ms; null when absent/invalid.\n */\nfunction retryAfterMs(res: Response): number | null {\n const header = res.headers.get('retry-after')\n if (!header) return null\n const seconds = Number(header)\n return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : null\n}\n\n/**\n * POST with a per-attempt timeout and a bounded retry on 429/529 — honouring\n * `retry-after`, else exponential backoff. Timeouts/network errors retry too;\n * any other response is returned as-is for the caller to handle. The durable job\n * queue is the longer-term retry beyond {@link DEFAULT_MAX_RETRIES}.\n *\n * @param url\n * @param init\n * @param timeoutMs\n * @param maxRetries\n * @returns\n */\nasync function postWithRetry(url: string, init: RequestInit, timeoutMs: number, maxRetries: number): Promise<Response> {\n for (let attempt = 0; ; attempt++) {\n let res: Response\n try {\n res = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) })\n } catch (error) {\n if (attempt >= maxRetries) throw error\n await sleep(backoffMs(attempt))\n continue\n }\n if (RETRYABLE_STATUS.has(res.status) && attempt < maxRetries) {\n await sleep(retryAfterMs(res) ?? backoffMs(attempt))\n continue\n }\n return res\n }\n}\n\n/**\n * Build the default vision call against the Anthropic messages API.\n *\n * @param input\n * @returns\n */\nexport function anthropicVision(opts: {\n apiKey: string\n model: string\n baseUrl: string\n timeoutMs?: number\n maxRetries?: number\n}): AiVisionExtract {\n return async (request, images) => {\n const hint = request.documentType ? ` The document is a ${request.documentType}.` : ''\n const country = request.country ? ` Issuing country hint: ${request.country}.` : ''\n const res = await postWithRetry(\n `${opts.baseUrl}/v1/messages`,\n {\n method: 'POST',\n headers: {\n 'x-api-key': opts.apiKey,\n 'anthropic-version': '2023-06-01',\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n model: opts.model,\n max_tokens: 1024,\n system: SYSTEM_PROMPT,\n tools: [READ_TOOL],\n tool_choice: { type: 'tool', name: 'read_document' },\n messages: [\n {\n role: 'user',\n content: [\n ...images.map((img) => ({\n type: 'image',\n source: { type: 'base64', media_type: img.mediaType, data: img.data },\n })),\n { type: 'text', text: `Read this identity document and return its fields.${hint}${country}` },\n ],\n },\n ],\n }),\n },\n opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n opts.maxRetries ?? DEFAULT_MAX_RETRIES,\n )\n\n if (!res.ok) {\n throw new Error(`AnthropicOcrDriver request failed with status ${res.status}`)\n }\n\n const json = (await res.json()) as AnthropicResponse\n const tool = json.content?.find((block) => block.type === 'tool_use' && block.name === 'read_document')\n if (!tool?.input) {\n throw new Error('AnthropicOcrDriver: model returned no structured fields')\n }\n\n return mapToolInput(tool.input)\n }\n}\n\n/**\n * Minimal shape of the OpenAI-compatible chat-completions response we read.\n */\ninterface ChatCompletionResponse {\n choices?: Array<{\n message?: {\n content?: string | null\n tool_calls?: Array<{ function?: { name?: string; arguments?: string | Record<string, unknown> } }>\n }\n }>\n}\n\n/**\n * Parse a JSON object out of model text, tolerating a ```json fence. Null when\n * the text holds no object.\n *\n * @param text\n * @returns\n */\nfunction parseJsonObject(text: string | null | undefined): Record<string, unknown> | null {\n if (!text) return null\n const start = text.indexOf('{')\n const end = text.lastIndexOf('}')\n if (start < 0 || end <= start) return null\n try {\n const parsed = JSON.parse(text.slice(start, end + 1)) as unknown\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null\n } catch {\n return null\n }\n}\n\n/**\n * Build the vision call against Cloudflare Workers AI's OpenAI-compatible chat\n * completions endpoint. Images go in as base64 data URLs and the model is forced\n * to call `read_document`; when a model answers in plain text instead, a JSON\n * object in the reply is accepted as the tool input.\n *\n * @param opts\n * @returns\n */\nexport function workersAiVision(opts: {\n apiKey: string\n model: string\n /** OpenAI-compatible base ending in `/v1`. */\n baseUrl: string\n timeoutMs?: number\n maxRetries?: number\n}): AiVisionExtract {\n return async (request, images) => {\n const hint = request.documentType ? ` The document is a ${request.documentType}.` : ''\n const country = request.country ? ` Issuing country hint: ${request.country}.` : ''\n const res = await postWithRetry(\n `${opts.baseUrl}/chat/completions`,\n {\n method: 'POST',\n headers: {\n authorization: `Bearer ${opts.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n model: opts.model,\n max_completion_tokens: 2048,\n temperature: 0,\n tools: [\n {\n type: 'function',\n function: {\n name: READ_TOOL.name,\n description: READ_TOOL.description,\n parameters: READ_TOOL.input_schema,\n },\n },\n ],\n tool_choice: 'required',\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n {\n role: 'user',\n content: [\n ...images.map((img) => ({\n type: 'image_url',\n image_url: { url: `data:${img.mediaType};base64,${img.data}` },\n })),\n { type: 'text', text: `Read this identity document and return its fields.${hint}${country}` },\n ],\n },\n ],\n }),\n },\n opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n opts.maxRetries ?? DEFAULT_MAX_RETRIES,\n )\n\n if (!res.ok) {\n throw new Error(`AnthropicOcrDriver (workers-ai) request failed with status ${res.status}`)\n }\n\n const message = ((await res.json()) as ChatCompletionResponse).choices?.[0]?.message\n const call = message?.tool_calls?.find((c) => c.function?.name === READ_TOOL.name) ?? message?.tool_calls?.[0]\n const args = call?.function?.arguments\n const input = typeof args === 'string' ? parseJsonObject(args) : (args ?? parseJsonObject(message?.content))\n if (!input) {\n throw new Error('AnthropicOcrDriver (workers-ai): model returned no structured fields')\n }\n\n return mapToolInput(input)\n }\n}\n\n/**\n * Coerce the model's tool input into an {@link AiExtraction} (string-typed fields).\n *\n * @param input\n * @returns\n */\nfunction mapToolInput(input: Record<string, unknown>): AiExtraction {\n const str = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v.trim() : undefined)\n const docType = str(input.documentType)\n return {\n fields: {\n firstName: str(input.firstName),\n lastName: str(input.lastName),\n fullName: str(input.fullName),\n dateOfBirth: str(input.dateOfBirth),\n documentNumber: str(input.documentNumber),\n expiryDate: str(input.expiryDate),\n nationality: str(input.nationality),\n },\n legibility: typeof input.legibility === 'number' ? input.legibility : undefined,\n documentType: docType && (DOCUMENT_TYPES as readonly string[]).includes(docType) ? (docType as DocumentType) : null,\n authenticity: mapAuthenticity(input),\n }\n}\n\n/**\n * Build the {@link OcrAuthenticity} read from the model's tool input. Returns\n * `undefined` when the model reported nothing assessable (no flags, no\n * confidence, no notes) so a driver that can't see authenticity stays silent.\n *\n * @param input\n * @returns\n */\nfunction mapAuthenticity(input: Record<string, unknown>): OcrAuthenticity | undefined {\n const bool = (v: unknown): boolean => v === true\n const screenReplay = bool(input.screenReplay)\n const photocopy = bool(input.photocopy)\n const digitalTampering = bool(input.digitalTampering)\n const physicalTampering = bool(input.physicalTampering)\n const flagged = screenReplay || photocopy || digitalTampering || physicalTampering\n\n const observations = Array.isArray(input.authenticityObservations)\n ? input.authenticityObservations\n .filter((o): o is string => typeof o === 'string' && o.trim().length > 0)\n .map((o) => o.trim())\n .slice(0, 6)\n : []\n\n const reported = typeof input.authenticityConfidence === 'number'\n // The model said nothing about authenticity at all — don't fabricate a verdict.\n if (!flagged && !reported && observations.length === 0) return undefined\n\n // A flagged document with no explicit score defaults to clearly-suspect (0.2);\n // an unflagged read defaults to clearly-genuine (1).\n const confidence = clamp01(reported ? (input.authenticityConfidence as number) : flagged ? 0.2 : 1)\n\n return { genuine: !flagged, confidence, screenReplay, photocopy, digitalTampering, physicalTampering, observations }\n}\n\n/**\n * Detect the media type from magic bytes; default to JPEG.\n *\n * @param bytes\n * @returns\n */\nfunction detectMediaType(bytes: Uint8Array): PreparedImage['mediaType'] {\n if (bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg'\n if (bytes[0] === 0x89 && bytes[1] === 0x50) return 'image/png'\n if (bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[8] === 0x57) return 'image/webp'\n return 'image/jpeg'\n}\n\ninterface SharpInstance {\n metadata(): Promise<{ width?: number; height?: number }>\n resize(options: { width?: number; height?: number; fit: string; withoutEnlargement: boolean }): SharpInstance\n jpeg(options: { quality: number }): SharpInstance\n toBuffer(): Promise<Buffer>\n}\ntype SharpFactory = (input: Buffer) => SharpInstance\n\nlet sharpFactory: SharpFactory | null | undefined\n\n/** Lazily resolve the optional `sharp` factory once; null when not installed. */\nasync function loadSharp(): Promise<SharpFactory | null> {\n if (sharpFactory !== undefined) return sharpFactory\n const moduleName = 'sharp'\n try {\n const mod = (await import(/* @vite-ignore */ moduleName)) as unknown as { default: SharpFactory }\n sharpFactory = mod.default\n } catch {\n sharpFactory = null\n }\n return sharpFactory\n}\n\n/**\n * Downscale an image to `maxEdge` and re-encode as JPEG to bound the upload (and\n * therefore the model's image-token cost). Falls back to the original bytes when\n * `sharp` isn't installed or fails — the API caps oversized images itself.\n *\n * @param url\n * @param init\n * @param timeoutMs\n * @param maxRetries\n * @returns\n */\nasync function prepareImage(bytes: Uint8Array, maxEdge: number): Promise<PreparedImage> {\n const sharp = await loadSharp()\n if (sharp) {\n try {\n const input = Buffer.from(bytes)\n const { width, height } = await sharp(input).metadata()\n const longest = Math.max(width ?? 0, height ?? 0)\n let pipe = sharp(input)\n if (longest > maxEdge) {\n pipe = pipe.resize({ width: maxEdge, height: maxEdge, fit: 'inside', withoutEnlargement: true })\n }\n const out = await pipe.jpeg({ quality: 85 }).toBuffer()\n return { mediaType: 'image/jpeg', data: out.toString('base64') }\n } catch {\n // fall through to raw bytes\n }\n }\n return { mediaType: detectMediaType(bytes), data: Buffer.from(bytes).toString('base64') }\n}\n"],"mappings":";AAGA,MAAM,WAAW,MAAsB,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,CAAC,CAAC;;;;AAKjE,MAAM,mBAAmB;;;;AAKzB,MAAa,mBAAmB;;;;AAKhC,MAAa,2BAA2B;;;;;;AAYxC,MAAM,mBAAmB;;;;AAKzB,MAAM,qBAAqB;;;;AAK3B,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;AAuE5B,IAAa,qBAAb,MAAqD;CACnD,OAAgB;CAEhB;CACA;CACA;CACA;CAEA,YAAY,UAA+B,CAAC,GAAG;EAC7C,KAAK,WAAW,QAAQ,YAAY;EACpC,IAAI,CAAC,QAAQ,UAAU,CAAC,QAAQ,SAC9B,MAAM,IAAI,MAAM,2CAA2C;EAE7D,KAAK,QAAQ,QAAQ,UAAU,KAAK,aAAa,eAAA,kCAAA;EACjD,KAAK,UAAU,QAAQ,WAAW;EAElC,MAAM,YAAY,QAAQ,aAAa;EACvC,MAAM,aAAa,QAAQ,cAAc;EACzC,IAAI,QAAQ,SACV,KAAK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AC/B,MAAM,EAAE,OAAO,WAAW,MAAM,MAAM,KAAK,CAAC,CAAC,SAAS;EACtD,MAAM,UAAU,KAAK,IAAI,SAAS,GAAG,UAAU,CAAC;EAChD,IAAI,OAAO,MAAM,KAAK;EACtB,IAAI,UAAU,SACZ,OAAO,KAAK,OAAO;GAAE,OAAO;GAAS,QAAQ;GAAS,KAAK;GAAU,oBAAoB;EAAK,CAAC;EAGjG,OAAO;GAAE,WAAW;GAAc,OAAM,MADtB,KAAK,KAAK,EAAE,SAAS,GAAG,CAAC,CAAC,CAAC,SAAS,EAAA,CACV,SAAS,QAAQ;EAAE;CACjE,QAAQ,CAER;CAEF,OAAO;EAAE,WAAW,gBAAgB,KAAK;EAAG,MAAM,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,QAAQ;CAAE;AAC1F"}
|
|
1
|
+
{"version":3,"file":"ai.mjs","names":[],"sources":["../../src/drivers/ai.ts"],"sourcesContent":["import type { DocumentType, OcrAuthenticity, OcrFields, OcrResultData } from '@arkyc/types'\nimport type { OcrDriver, OcrRequest } from '../types'\n\nconst clamp01 = (n: number): number => Math.min(1, Math.max(0, n))\n\n/**\n * Anthropic's default API base; override for a gateway/proxy.\n */\nconst DEFAULT_BASE_URL = 'https://api.anthropic.com'\n\n/**\n * A small, cheap vision model is plenty for reading printed/MRZ document text.\n */\nexport const DEFAULT_AI_MODEL = 'claude-haiku-4-5-20251001'\n\n/**\n * Default Cloudflare Workers AI model: Gemma 4 accepts image input and tool calls.\n */\nexport const DEFAULT_WORKERS_AI_MODEL = '@cf/google/gemma-4-26b-a4b-it'\n\n/**\n * Which hosted vision API backs the `ai` driver.\n */\nexport type AiOcrProvider = 'anthropic' | 'workers-ai'\n\n/**\n * Longest edge (px) we upload. The API downsamples anything larger anyway and\n * bills by the resampled size, so this is a cost/bandwidth bound, not a quality\n * one — small enough to be cheap, large enough to keep the MRZ legible.\n */\nconst DEFAULT_MAX_EDGE = 1568\n\n/**\n * Per-attempt request timeout (ms) — a hung connection must not stall a worker.\n */\nconst DEFAULT_TIMEOUT_MS = 30_000\n\n/**\n * Bounded in-driver retries on rate-limit/overload; the job queue retries beyond.\n */\nconst DEFAULT_MAX_RETRIES = 2\n\n/**\n * A base64 image ready for the messages API, with its detected media type.\n */\ninterface PreparedImage {\n mediaType: 'image/jpeg' | 'image/png' | 'image/webp'\n data: string\n}\n\n/**\n * Raw fields the vision model returned, before validation/scoring.\n */\nexport interface AiExtraction {\n fields: OcrFields\n /** The model's own legibility self-assessment in [0, 1], if it gave one. */\n legibility?: number\n documentType?: DocumentType | null\n /** Best-effort tamper/replay read; omitted when the model reported nothing. */\n authenticity?: OcrAuthenticity\n /** The model's own tool-call arguments, kept for debugging what it actually returned. */\n modelOutput?: Record<string, unknown>\n}\n\n/**\n * Calls a vision model and returns the raw extracted fields. Injected so the\n * driver's scoring can be unit-tested without a network call; the default\n * implementation talks to the Anthropic messages API.\n */\nexport type AiVisionExtract = (request: OcrRequest, images: PreparedImage[]) => Promise<AiExtraction>\n\nexport interface AnthropicOcrOptions {\n /** Vision backend; defaults to `anthropic`. */\n provider?: AiOcrProvider\n /** Anthropic API key, or the Cloudflare API token for `workers-ai`. */\n apiKey?: string\n /** Cloudflare account id; required for `workers-ai` unless `baseUrl` is set. */\n accountId?: string\n /** Model id; defaults to {@link DEFAULT_AI_MODEL} or {@link DEFAULT_WORKERS_AI_MODEL}. */\n model?: string\n /**\n * API base URL. Anthropic: defaults to {@link DEFAULT_BASE_URL}. Workers AI: the\n * OpenAI-compatible base ending in `/v1` (e.g. an AI Gateway URL), defaulting to\n * the account's `/ai/v1` endpoint.\n */\n baseUrl?: string\n /** Longest image edge (px) to upload; defaults to {@link DEFAULT_MAX_EDGE}. */\n maxEdge?: number\n /** Per-attempt request timeout (ms); defaults to {@link DEFAULT_TIMEOUT_MS}. */\n timeoutMs?: number\n /** Bounded retries on 429/529; defaults to {@link DEFAULT_MAX_RETRIES}. */\n maxRetries?: number\n /** Override the vision call (tests). When set, `apiKey` is not required. */\n extract?: AiVisionExtract\n}\n\n/**\n * AI OCR driver: hands the document image(s) to a vision LLM (Claude by default,\n * or a Cloudflare Workers AI model with `provider: 'workers-ai'`) and maps the structured response onto {@link OcrResultData}.\n *\n * Confidence is **not** taken from the model's self-report — LLMs are poorly\n * calibrated and will state high confidence on hallucinated fields. Instead it's\n * derived deterministically from which fields came back and whether they're\n * structurally valid (see {@link scoreConfidence}), so the value feeding the\n * decision engine's `ocrConfidenceThreshold` is meaningful. The model's own\n * legibility read is folded in only as a small soft penalty.\n *\n * It also asks the model for a best-effort, image-only authenticity read\n * (screen-replay, photocopy, digital/physical tampering). That signal is\n * advisory: a fired flag only *caps* the OCR confidence (see\n * {@link applyAuthenticity}) so a suspicious document routes to manual review —\n * an LLM's authenticity guess never auto-rejects a user on its own.\n */\nexport class AnthropicOcrDriver implements OcrDriver {\n readonly name = 'ai'\n\n private readonly provider: AiOcrProvider\n private readonly model: string\n private readonly maxEdge: number\n private readonly vision: AiVisionExtract\n\n constructor(options: AnthropicOcrOptions = {}) {\n this.provider = options.provider ?? 'anthropic'\n if (!options.apiKey && !options.extract) {\n throw new Error('AnthropicOcrDriver requires config.apiKey')\n }\n this.model = options.model ?? (this.provider === 'workers-ai' ? DEFAULT_WORKERS_AI_MODEL : DEFAULT_AI_MODEL)\n this.maxEdge = options.maxEdge ?? DEFAULT_MAX_EDGE\n\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES\n if (options.extract) {\n this.vision = options.extract\n } else if (this.provider === 'workers-ai') {\n if (!options.accountId && !options.baseUrl) {\n throw new Error('AnthropicOcrDriver (workers-ai) requires config.accountId')\n }\n this.vision = workersAiVision({\n apiKey: options.apiKey as string,\n model: this.model,\n baseUrl: (\n options.baseUrl ?? `https://api.cloudflare.com/client/v4/accounts/${options.accountId}/ai/v1`\n ).replace(/\\/$/, ''),\n timeoutMs,\n maxRetries,\n })\n } else {\n this.vision = anthropicVision({\n apiKey: options.apiKey as string,\n model: this.model,\n baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, ''),\n timeoutMs,\n maxRetries,\n })\n }\n }\n\n async extract(request: OcrRequest): Promise<OcrResultData> {\n const images = await this.prepareImages(request)\n const raw = await this.vision(request, images)\n const fields = normalizeFields(raw.fields)\n const authenticity = raw.authenticity\n const confidence = applyAuthenticity(scoreConfidence(fields, raw.legibility), authenticity)\n\n return {\n fields,\n confidence,\n ...(authenticity ? { authenticity } : {}),\n raw: {\n provider: 'ai',\n backend: this.provider,\n model: this.model,\n legibility: raw.legibility ?? null,\n documentType: raw.documentType ?? request.documentType ?? null,\n authenticity: authenticity ?? null,\n modelOutput: raw.modelOutput ?? null,\n },\n }\n }\n\n /**\n * Resize (best-effort) and base64-encode the front + optional back images.\n *\n * @param input\n * @returns\n */\n private async prepareImages(request: OcrRequest): Promise<PreparedImage[]> {\n const sources = [request.image, request.backImage].filter((b): b is Uint8Array => !!b && b.length > 0)\n return Promise.all(sources.map((bytes) => prepareImage(bytes, this.maxEdge)))\n }\n}\n\nconst present = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0\nconst isIsoDate = (v: unknown): boolean => present(v) && /^\\d{4}-\\d{2}-\\d{2}$/.test(v) && !Number.isNaN(Date.parse(v))\n\n/**\n * Trim/blank-out the model's fields; drop anything empty so callers see `undefined`.\n *\n * @param input\n * @returns\n */\nfunction normalizeFields(fields: OcrFields): OcrFields {\n const out: OcrFields = {}\n const set = (key: keyof OcrFields, value: string | undefined) => {\n if (present(value)) out[key] = value.trim()\n }\n set('firstName', fields.firstName)\n set('lastName', fields.lastName)\n set('fullName', fields.fullName)\n set('dateOfBirth', fields.dateOfBirth)\n set('documentNumber', fields.documentNumber)\n set('expiryDate', fields.expiryDate)\n set('issueDate', fields.issueDate)\n set('nationality', fields.nationality)\n return out\n}\n\n/**\n * Deterministic confidence in [0, 1] from field completeness + structural\n * validity. Weights sum to 1.0 when every field is present and well-formed; the\n * model's self-reported legibility can only pull the score down by up to 15%, so\n * trustworthy structure dominates an unreliable self-assessment.\n *\n * @param fields\n * @param legibility\n * @returns\n */\nexport function scoreConfidence(fields: OcrFields, legibility?: number): number {\n const hasName = (present(fields.firstName) && present(fields.lastName)) || present(fields.fullName)\n const checks: Array<[boolean, number]> = [\n [hasName, 0.28],\n [isIsoDate(fields.dateOfBirth), 0.22],\n [present(fields.documentNumber) && fields.documentNumber!.trim().length >= 4, 0.22],\n [isIsoDate(fields.expiryDate), 0.16],\n [present(fields.nationality), 0.12],\n ]\n const base = checks.reduce((sum, [ok, weight]) => (ok ? sum + weight : sum), 0)\n const legible = clamp01(legibility ?? 1)\n return clamp01(base * (0.85 + 0.15 * legible))\n}\n\n/**\n * Hard ceiling on OCR confidence once any authenticity flag fires. Below the\n * default `ocrConfidenceThreshold` (0.8), so a flagged document routes to manual\n * review regardless of how cleanly its fields read.\n */\nconst SUSPECT_CONFIDENCE_CEILING = 0.5\n\n/**\n * Fold the authenticity read into the field-derived confidence. Only ever lowers\n * the score, and only when a concrete flag fired — a genuine (or unassessed)\n * document is returned untouched. A flagged document is capped at both the\n * model's own authenticity confidence and {@link SUSPECT_CONFIDENCE_CEILING},\n * which lands it in manual review rather than auto-approval. This is deliberately\n * conservative: the LLM's authenticity guess can demote, never reject outright.\n *\n * @param fieldScore\n * @param authenticity\n * @returns\n */\nexport function applyAuthenticity(fieldScore: number, authenticity?: OcrAuthenticity): number {\n if (!authenticity || authenticity.genuine) return fieldScore\n return Math.min(fieldScore, clamp01(authenticity.confidence), SUSPECT_CONFIDENCE_CEILING)\n}\n\nconst SYSTEM_PROMPT =\n 'You are an OCR engine for identity documents. Read the visible printed text and ' +\n 'the machine-readable zone (MRZ) if present, and return the fields exactly as ' +\n 'printed. Do not guess, infer, or correct values you cannot clearly read — omit a ' +\n 'field rather than fabricate it. Dates must be ISO 8601 (YYYY-MM-DD).\\n\\n' +\n 'Identity documents print BOTH a date of issue and a date of expiry — never ' +\n 'confuse them. `expiryDate` is only the expiry/expiration/\"valid until\"/\"date of ' +\n 'expiry\" value (in an MRZ, the second date field, not the first). `issueDate` is ' +\n 'the \"date of issue\"/\"issued\"/\"valid from\" value. The expiry is later than the ' +\n 'issue date. If a document shows only an issue date and no expiry, return the ' +\n 'issue date in `issueDate` and leave `expiryDate` empty — do not put the issue ' +\n 'date in `expiryDate`.\\n\\n' +\n 'ALSO assess document authenticity, to the best of your ability, from the image ' +\n 'alone — and report it. Be conservative: raise a flag only on a clear, visible ' +\n 'sign. A genuine document that was merely photographed imperfectly (blur, glare ' +\n 'on a glossy original, a shadow, a crop) must NOT be flagged. Set `screenReplay` ' +\n 'when the image looks like a photo of a screen — moiré or a visible pixel grid, ' +\n 'backlit glow, refresh banding, or a device bezel (a replay attack). Set ' +\n '`photocopy` when it looks like a photo or scan of a printout/photocopy rather ' +\n 'than the physical document — flat matte paper, halftone dot printing, no ' +\n 'security features or hologram. Set `digitalTampering` for signs of digital ' +\n 'editing — mismatched fonts or kerning, misaligned or recoloured text, smudged ' +\n 'or cloned regions, a pasted-in portrait, or altered dates. Set ' +\n '`physicalTampering` for a substituted photo, peeled or lifted laminate, or ' +\n 'scratched-out / overwritten fields. Give `authenticityConfidence` from 0 ' +\n '(clearly fake or replayed) to 1 (clearly an authentic original), and list brief ' +\n 'supporting notes in `authenticityObservations`. You read and assess the ' +\n 'document; you do not make the final accept/reject decision.'\n\nconst READ_TOOL = {\n name: 'read_document',\n description: 'Return the identity fields read from the document image(s).',\n input_schema: {\n type: 'object',\n properties: {\n firstName: { type: 'string', description: 'Given name(s) as printed.' },\n lastName: { type: 'string', description: 'Surname / family name as printed.' },\n fullName: { type: 'string', description: 'Full name if given/surname cannot be separated.' },\n dateOfBirth: { type: 'string', description: 'Date of birth, ISO 8601 YYYY-MM-DD.' },\n documentNumber: {\n type: 'string',\n description:\n 'Document/serial number as printed; for a national ID card or slip, the national identification number (e.g. NIN).',\n },\n issueDate: {\n type: 'string',\n description: 'Date of issue (\"issued\"/\"valid from\"/\"issue date\"), ISO 8601 YYYY-MM-DD. NOT the expiry.',\n },\n expiryDate: {\n type: 'string',\n description:\n 'Expiry date (\"date of expiry\"/\"valid until\"/\"expiry date\"), ISO 8601 YYYY-MM-DD. Must be the expiry, never the issue date; omit if the document shows no expiry.',\n },\n nationality: { type: 'string', description: 'ISO 3166-1 alpha-3 country code if determinable.' },\n documentType: {\n type: 'string',\n enum: ['passport', 'id_card', 'drivers_license', 'residence_permit'],\n },\n legibility: {\n type: 'number',\n description: 'How clearly the document text could be read, 0 (illegible) to 1 (crisp).',\n },\n screenReplay: {\n type: 'boolean',\n description: 'Looks like a photo of a screen (moiré, pixel grid, backlit glow, refresh banding, bezel).',\n },\n photocopy: {\n type: 'boolean',\n description: 'Looks like a photo/scan of a printout or photocopy rather than the physical document.',\n },\n digitalTampering: {\n type: 'boolean',\n description:\n 'Signs of digital editing: mismatched fonts, misaligned/recoloured text, cloned regions, edited photo/dates.',\n },\n physicalTampering: {\n type: 'boolean',\n description:\n 'Signs of physical tampering: substituted photo, peeled laminate, scratched-out/overwritten fields.',\n },\n authenticityConfidence: {\n type: 'number',\n description: 'Authenticity confidence, 0 (clearly fake/replayed) to 1 (clearly an authentic original).',\n },\n authenticityObservations: {\n type: 'array',\n items: { type: 'string' },\n description: 'Brief notes supporting any authenticity flag raised.',\n },\n },\n },\n} as const\n\n/**\n * Minimal shape of the messages-API response we read.\n *\n */\ninterface AnthropicResponse {\n content?: Array<{ type: string; name?: string; input?: Record<string, unknown> }>\n}\n\nconst DOCUMENT_TYPES: readonly DocumentType[] = ['passport', 'id_card', 'drivers_license', 'residence_permit']\n\n/**\n * HTTP statuses worth a bounded retry: rate-limited / overloaded / unavailable.\n */\nconst RETRYABLE_STATUS = new Set([429, 503, 529])\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))\n\n/**\n * Exponential backoff (ms) for attempt 0, 1, 2…, capped at 8s.\n */\nconst backoffMs = (attempt: number): number => Math.min(8_000, 500 * 2 ** attempt)\n\n/**\n * Parse a `retry-after` header (seconds) into ms; null when absent/invalid.\n */\nfunction retryAfterMs(res: Response): number | null {\n const header = res.headers.get('retry-after')\n if (!header) return null\n const seconds = Number(header)\n return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : null\n}\n\n/**\n * POST with a per-attempt timeout and a bounded retry on 429/529 — honouring\n * `retry-after`, else exponential backoff. Timeouts/network errors retry too;\n * any other response is returned as-is for the caller to handle. The durable job\n * queue is the longer-term retry beyond {@link DEFAULT_MAX_RETRIES}.\n *\n * @param url\n * @param init\n * @param timeoutMs\n * @param maxRetries\n * @returns\n */\nasync function postWithRetry(url: string, init: RequestInit, timeoutMs: number, maxRetries: number): Promise<Response> {\n for (let attempt = 0; ; attempt++) {\n let res: Response\n try {\n res = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) })\n } catch (error) {\n if (attempt >= maxRetries) throw error\n await sleep(backoffMs(attempt))\n continue\n }\n if (RETRYABLE_STATUS.has(res.status) && attempt < maxRetries) {\n await sleep(retryAfterMs(res) ?? backoffMs(attempt))\n continue\n }\n return res\n }\n}\n\n/**\n * Build the default vision call against the Anthropic messages API.\n *\n * @param input\n * @returns\n */\nexport function anthropicVision(opts: {\n apiKey: string\n model: string\n baseUrl: string\n timeoutMs?: number\n maxRetries?: number\n}): AiVisionExtract {\n return async (request, images) => {\n const hint = request.documentType ? ` The document is a ${request.documentType}.` : ''\n const country = request.country ? ` Issuing country hint: ${request.country}.` : ''\n const res = await postWithRetry(\n `${opts.baseUrl}/v1/messages`,\n {\n method: 'POST',\n headers: {\n 'x-api-key': opts.apiKey,\n 'anthropic-version': '2023-06-01',\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n model: opts.model,\n max_tokens: 1024,\n system: SYSTEM_PROMPT,\n tools: [READ_TOOL],\n tool_choice: { type: 'tool', name: 'read_document' },\n messages: [\n {\n role: 'user',\n content: [\n ...images.map((img) => ({\n type: 'image',\n source: { type: 'base64', media_type: img.mediaType, data: img.data },\n })),\n { type: 'text', text: `Read this identity document and return its fields.${hint}${country}` },\n ],\n },\n ],\n }),\n },\n opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n opts.maxRetries ?? DEFAULT_MAX_RETRIES,\n )\n\n if (!res.ok) {\n throw new Error(`AnthropicOcrDriver request failed with status ${res.status}`)\n }\n\n const json = (await res.json()) as AnthropicResponse\n const tool = json.content?.find((block) => block.type === 'tool_use' && block.name === 'read_document')\n if (!tool?.input) {\n throw new Error('AnthropicOcrDriver: model returned no structured fields')\n }\n\n return mapToolInput(tool.input)\n }\n}\n\n/**\n * Minimal shape of the OpenAI-compatible chat-completions response we read.\n */\ninterface ChatCompletionResponse {\n choices?: Array<{\n message?: {\n content?: string | null\n tool_calls?: Array<{ function?: { name?: string; arguments?: string | Record<string, unknown> } }>\n }\n }>\n}\n\n/**\n * Parse a JSON object out of model text, tolerating a ```json fence. Null when\n * the text holds no object.\n *\n * @param text\n * @returns\n */\nfunction parseJsonObject(text: string | null | undefined): Record<string, unknown> | null {\n if (!text) return null\n const start = text.indexOf('{')\n const end = text.lastIndexOf('}')\n if (start < 0 || end <= start) return null\n try {\n const parsed = JSON.parse(text.slice(start, end + 1)) as unknown\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null\n } catch {\n return null\n }\n}\n\n/**\n * Build the vision call against Cloudflare Workers AI's OpenAI-compatible chat\n * completions endpoint. Images go in as base64 data URLs and the model is forced\n * to call `read_document`; when a model answers in plain text instead, a JSON\n * object in the reply is accepted as the tool input.\n *\n * @param opts\n * @returns\n */\nexport function workersAiVision(opts: {\n apiKey: string\n model: string\n /** OpenAI-compatible base ending in `/v1`. */\n baseUrl: string\n timeoutMs?: number\n maxRetries?: number\n}): AiVisionExtract {\n return async (request, images) => {\n const hint = request.documentType ? ` The document is a ${request.documentType}.` : ''\n const country = request.country ? ` Issuing country hint: ${request.country}.` : ''\n const res = await postWithRetry(\n `${opts.baseUrl}/chat/completions`,\n {\n method: 'POST',\n headers: {\n authorization: `Bearer ${opts.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n model: opts.model,\n max_completion_tokens: 2048,\n temperature: 0,\n tools: [\n {\n type: 'function',\n function: {\n name: READ_TOOL.name,\n description: READ_TOOL.description,\n parameters: READ_TOOL.input_schema,\n },\n },\n ],\n tool_choice: 'required',\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n {\n role: 'user',\n content: [\n ...images.map((img) => ({\n type: 'image_url',\n image_url: { url: `data:${img.mediaType};base64,${img.data}` },\n })),\n { type: 'text', text: `Read this identity document and return its fields.${hint}${country}` },\n ],\n },\n ],\n }),\n },\n opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n opts.maxRetries ?? DEFAULT_MAX_RETRIES,\n )\n\n if (!res.ok) {\n throw new Error(`AnthropicOcrDriver (workers-ai) request failed with status ${res.status}`)\n }\n\n const message = ((await res.json()) as ChatCompletionResponse).choices?.[0]?.message\n const call = message?.tool_calls?.find((c) => c.function?.name === READ_TOOL.name) ?? message?.tool_calls?.[0]\n const args = call?.function?.arguments\n const input = typeof args === 'string' ? parseJsonObject(args) : (args ?? parseJsonObject(message?.content))\n if (!input) {\n throw new Error('AnthropicOcrDriver (workers-ai): model returned no structured fields')\n }\n\n return mapToolInput(input)\n }\n}\n\n/**\n * Coerce the model's tool input into an {@link AiExtraction} (string-typed fields).\n *\n * @param input\n * @returns\n */\nfunction mapToolInput(input: Record<string, unknown>): AiExtraction {\n const str = (v: unknown): string | undefined => {\n if (typeof v === 'number' && Number.isFinite(v)) return String(v)\n\n return typeof v === 'string' && v.trim() ? v.trim() : undefined\n }\n // Models don't always use the schema's exact keys (snake_case, `surname`, a\n // national-ID label like `nin`) or may nest them under `fields`; read the first\n // alias present so a correct read isn't discarded over naming.\n const nested = input.fields && typeof input.fields === 'object' ? (input.fields as Record<string, unknown>) : {}\n const source = { ...nested, ...input }\n const pick = (...keys: string[]): string | undefined => {\n for (const key of keys) {\n const value = str(source[key])\n if (value) return value\n }\n\n return undefined\n }\n const docType = str(input.documentType)\n return {\n modelOutput: input,\n fields: {\n firstName: pick('firstName', 'first_name', 'givenName', 'givenNames', 'given_names', 'forename', 'forenames'),\n lastName: pick('lastName', 'last_name', 'surname', 'familyName', 'family_name'),\n fullName: pick('fullName', 'full_name', 'name'),\n dateOfBirth: pick('dateOfBirth', 'date_of_birth', 'dob', 'birthDate', 'birth_date'),\n documentNumber: pick(\n 'documentNumber',\n 'document_number',\n 'idNumber',\n 'id_number',\n 'nin',\n 'nationalIdNumber',\n 'national_id_number',\n 'number',\n ),\n expiryDate: pick('expiryDate', 'expiry_date', 'dateOfExpiry', 'date_of_expiry', 'expiry'),\n nationality: pick('nationality'),\n },\n legibility: typeof input.legibility === 'number' ? input.legibility : undefined,\n documentType: docType && (DOCUMENT_TYPES as readonly string[]).includes(docType) ? (docType as DocumentType) : null,\n authenticity: mapAuthenticity(input),\n }\n}\n\n/**\n * Build the {@link OcrAuthenticity} read from the model's tool input. Returns\n * `undefined` when the model reported nothing assessable (no flags, no\n * confidence, no notes) so a driver that can't see authenticity stays silent.\n *\n * @param input\n * @returns\n */\nfunction mapAuthenticity(input: Record<string, unknown>): OcrAuthenticity | undefined {\n const bool = (v: unknown): boolean => v === true\n const screenReplay = bool(input.screenReplay)\n const photocopy = bool(input.photocopy)\n const digitalTampering = bool(input.digitalTampering)\n const physicalTampering = bool(input.physicalTampering)\n const flagged = screenReplay || photocopy || digitalTampering || physicalTampering\n\n const observations = Array.isArray(input.authenticityObservations)\n ? input.authenticityObservations\n .filter((o): o is string => typeof o === 'string' && o.trim().length > 0)\n .map((o) => o.trim())\n .slice(0, 6)\n : []\n\n const reported = typeof input.authenticityConfidence === 'number'\n // The model said nothing about authenticity at all — don't fabricate a verdict.\n if (!flagged && !reported && observations.length === 0) return undefined\n\n // A flagged document with no explicit score defaults to clearly-suspect (0.2);\n // an unflagged read defaults to clearly-genuine (1).\n const confidence = clamp01(reported ? (input.authenticityConfidence as number) : flagged ? 0.2 : 1)\n\n return { genuine: !flagged, confidence, screenReplay, photocopy, digitalTampering, physicalTampering, observations }\n}\n\n/**\n * Detect the media type from magic bytes; default to JPEG.\n *\n * @param bytes\n * @returns\n */\nfunction detectMediaType(bytes: Uint8Array): PreparedImage['mediaType'] {\n if (bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg'\n if (bytes[0] === 0x89 && bytes[1] === 0x50) return 'image/png'\n if (bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[8] === 0x57) return 'image/webp'\n return 'image/jpeg'\n}\n\ninterface SharpInstance {\n metadata(): Promise<{ width?: number; height?: number }>\n resize(options: { width?: number; height?: number; fit: string; withoutEnlargement: boolean }): SharpInstance\n jpeg(options: { quality: number }): SharpInstance\n toBuffer(): Promise<Buffer>\n}\ntype SharpFactory = (input: Buffer) => SharpInstance\n\nlet sharpFactory: SharpFactory | null | undefined\n\n/** Lazily resolve the optional `sharp` factory once; null when not installed. */\nasync function loadSharp(): Promise<SharpFactory | null> {\n if (sharpFactory !== undefined) return sharpFactory\n const moduleName = 'sharp'\n try {\n const mod = (await import(/* @vite-ignore */ moduleName)) as unknown as { default: SharpFactory }\n sharpFactory = mod.default\n } catch {\n sharpFactory = null\n }\n return sharpFactory\n}\n\n/**\n * Downscale an image to `maxEdge` and re-encode as JPEG to bound the upload (and\n * therefore the model's image-token cost). Falls back to the original bytes when\n * `sharp` isn't installed or fails — the API caps oversized images itself.\n *\n * @param url\n * @param init\n * @param timeoutMs\n * @param maxRetries\n * @returns\n */\nasync function prepareImage(bytes: Uint8Array, maxEdge: number): Promise<PreparedImage> {\n const sharp = await loadSharp()\n if (sharp) {\n try {\n const input = Buffer.from(bytes)\n const { width, height } = await sharp(input).metadata()\n const longest = Math.max(width ?? 0, height ?? 0)\n let pipe = sharp(input)\n if (longest > maxEdge) {\n pipe = pipe.resize({ width: maxEdge, height: maxEdge, fit: 'inside', withoutEnlargement: true })\n }\n const out = await pipe.jpeg({ quality: 85 }).toBuffer()\n return { mediaType: 'image/jpeg', data: out.toString('base64') }\n } catch {\n // fall through to raw bytes\n }\n }\n return { mediaType: detectMediaType(bytes), data: Buffer.from(bytes).toString('base64') }\n}\n"],"mappings":";AAGA,MAAM,WAAW,MAAsB,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,CAAC,CAAC;;;;AAKjE,MAAM,mBAAmB;;;;AAKzB,MAAa,mBAAmB;;;;AAKhC,MAAa,2BAA2B;;;;;;AAYxC,MAAM,mBAAmB;;;;AAKzB,MAAM,qBAAqB;;;;AAK3B,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;AAyE5B,IAAa,qBAAb,MAAqD;CACnD,OAAgB;CAEhB;CACA;CACA;CACA;CAEA,YAAY,UAA+B,CAAC,GAAG;EAC7C,KAAK,WAAW,QAAQ,YAAY;EACpC,IAAI,CAAC,QAAQ,UAAU,CAAC,QAAQ,SAC9B,MAAM,IAAI,MAAM,2CAA2C;EAE7D,KAAK,QAAQ,QAAQ,UAAU,KAAK,aAAa,eAAA,kCAAA;EACjD,KAAK,UAAU,QAAQ,WAAW;EAElC,MAAM,YAAY,QAAQ,aAAa;EACvC,MAAM,aAAa,QAAQ,cAAc;EACzC,IAAI,QAAQ,SACV,KAAK,SAAS,QAAQ;OACjB,IAAI,KAAK,aAAa,cAAc;GACzC,IAAI,CAAC,QAAQ,aAAa,CAAC,QAAQ,SACjC,MAAM,IAAI,MAAM,2DAA2D;GAE7E,KAAK,SAAS,gBAAgB;IAC5B,QAAQ,QAAQ;IAChB,OAAO,KAAK;IACZ,UACE,QAAQ,WAAW,iDAAiD,QAAQ,UAAU,QAAA,CACtF,QAAQ,OAAO,EAAE;IACnB;IACA;GACF,CAAC;EACH,OACE,KAAK,SAAS,gBAAgB;GAC5B,QAAQ,QAAQ;GAChB,OAAO,KAAK;GACZ,UAAU,QAAQ,WAAW,iBAAA,CAAkB,QAAQ,OAAO,EAAE;GAChE;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AAmB,SAAyC;CACtF,MAAM,QAAQ,MAAM,UAAU;CAC9B,IAAI,OACF,IAAI;EACF,MAAM,QAAQ,OAAO,KAAK,KAAK;EAC/B,MAAM,EAAE,OAAO,WAAW,MAAM,MAAM,KAAK,CAAC,CAAC,SAAS;EACtD,MAAM,UAAU,KAAK,IAAI,SAAS,GAAG,UAAU,CAAC;EAChD,IAAI,OAAO,MAAM,KAAK;EACtB,IAAI,UAAU,SACZ,OAAO,KAAK,OAAO;GAAE,OAAO;GAAS,QAAQ;GAAS,KAAK;GAAU,oBAAoB;EAAK,CAAC;EAGjG,OAAO;GAAE,WAAW;GAAc,OAAM,MADtB,KAAK,KAAK,EAAE,SAAS,GAAG,CAAC,CAAC,CAAC,SAAS,EAAA,CACV,SAAS,QAAQ;EAAE;CACjE,QAAQ,CAER;CAEF,OAAO;EAAE,WAAW,gBAAgB,KAAK;EAAG,MAAM,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,QAAQ;CAAE;AAC1F"}
|
|
@@ -1,17 +1,15 @@
|
|
|
1
1
|
import { OcrConfig, OcrDriver, OcrRequest } from "../types.mjs";
|
|
2
2
|
import { OcrResultData } from "@arkyc/types";
|
|
3
|
-
|
|
4
3
|
//#region src/drivers/external.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* Generic HTTP OCR driver: POSTs the base64 image to a configured endpoint and
|
|
7
6
|
* expects an {@link OcrResultData}-shaped JSON response.
|
|
8
7
|
*/
|
|
9
|
-
declare class ExternalOcrDriver implements OcrDriver {
|
|
8
|
+
export declare class ExternalOcrDriver implements OcrDriver {
|
|
10
9
|
private readonly config;
|
|
11
10
|
readonly name = "external";
|
|
12
11
|
constructor(config: OcrConfig);
|
|
13
12
|
extract(request: OcrRequest): Promise<OcrResultData>;
|
|
14
13
|
}
|
|
15
14
|
//#endregion
|
|
16
|
-
export { ExternalOcrDriver };
|
|
17
15
|
//# sourceMappingURL=external.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external.d.mts","names":[],"sources":["../../src/drivers/external.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"external.d.mts","names":[],"sources":["../../src/drivers/external.ts"],"mappings":";;;;;;;qBAOa,6BAA6B;mBAGX;WAFpB;EAEoB,YAAA,QAAQ;EAI/B,QAAQ,SAAS,aAAa,QAAQ"}
|
package/dist/drivers/mock.d.mts
CHANGED
|
@@ -1,16 +1,14 @@
|
|
|
1
1
|
import { OcrDriver, OcrRequest } from "../types.mjs";
|
|
2
2
|
import { OcrResultData } from "@arkyc/types";
|
|
3
|
-
|
|
4
3
|
//#region src/drivers/mock.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* Deterministic OCR driver for development + tests. Returns fixed identity
|
|
7
6
|
* fields; `hints` steer the confidence and expiry so a caller can drive a
|
|
8
7
|
* session toward any decision.
|
|
9
8
|
*/
|
|
10
|
-
declare class MockOcrDriver implements OcrDriver {
|
|
9
|
+
export declare class MockOcrDriver implements OcrDriver {
|
|
11
10
|
readonly name = "mock";
|
|
12
11
|
extract(request: OcrRequest): Promise<OcrResultData>;
|
|
13
12
|
}
|
|
14
13
|
//#endregion
|
|
15
|
-
export { MockOcrDriver };
|
|
16
14
|
//# sourceMappingURL=mock.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mock.d.mts","names":[],"sources":["../../src/drivers/mock.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"mock.d.mts","names":[],"sources":["../../src/drivers/mock.ts"],"mappings":";;;;;;;;qBAUa,yBAAyB;WAC3B;EAEH,QAAQ,SAAS,aAAa,QAAQ"}
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
* unchanged) bytes — a preprocessor must never throw; on failure it returns the
|
|
5
5
|
* input so recognition still runs.
|
|
6
6
|
*/
|
|
7
|
-
type OcrPreprocessor = (image: Uint8Array) => Promise<Uint8Array>;
|
|
7
|
+
export type OcrPreprocessor = (image: Uint8Array) => Promise<Uint8Array>;
|
|
8
8
|
/** Tunables for the default {@link sharpPreprocessor}. */
|
|
9
|
-
interface PreprocessOptions {
|
|
9
|
+
export interface PreprocessOptions {
|
|
10
10
|
/**
|
|
11
11
|
* Upscale images narrower than this (px) to give the engine more pixels per
|
|
12
12
|
* glyph — the single biggest win for the small OCR-B MRZ band. Default 1600.
|
|
@@ -14,7 +14,7 @@ interface PreprocessOptions {
|
|
|
14
14
|
minWidth?: number;
|
|
15
15
|
}
|
|
16
16
|
/** A no-op preprocessor: passes the original bytes through unchanged. */
|
|
17
|
-
declare const passthrough: OcrPreprocessor;
|
|
17
|
+
export declare const passthrough: OcrPreprocessor;
|
|
18
18
|
/** Minimal structural type for the lazily-imported `sharp` module. */
|
|
19
19
|
interface SharpInstance {
|
|
20
20
|
metadata(): Promise<{
|
|
@@ -39,13 +39,13 @@ type SharpFactory = (input: Buffer) => SharpInstance;
|
|
|
39
39
|
* document text and the OCR-B MRZ band without the aggressive binarisation that
|
|
40
40
|
* destroys detail under uneven lighting. Any failure falls back to the original.
|
|
41
41
|
*/
|
|
42
|
-
declare function buildSharpPreprocessor(sharp: SharpFactory, options?: PreprocessOptions): OcrPreprocessor;
|
|
42
|
+
export declare function buildSharpPreprocessor(sharp: SharpFactory, options?: PreprocessOptions): OcrPreprocessor;
|
|
43
43
|
/**
|
|
44
44
|
* The default preprocessor, backed by the optional `sharp` package and resolved
|
|
45
45
|
* once. If `sharp` isn't installed it degrades to {@link passthrough}, so OCR
|
|
46
46
|
* still runs on the raw bytes (just without the legibility boost).
|
|
47
47
|
*/
|
|
48
|
-
declare function defaultPreprocessor(options?: PreprocessOptions): Promise<OcrPreprocessor>;
|
|
48
|
+
export declare function defaultPreprocessor(options?: PreprocessOptions): Promise<OcrPreprocessor>;
|
|
49
49
|
//#endregion
|
|
50
|
-
export {
|
|
50
|
+
export {};
|
|
51
51
|
//# sourceMappingURL=preprocess.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preprocess.d.mts","names":[],"sources":["../../src/drivers/preprocess.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"preprocess.d.mts","names":[],"sources":["../../src/drivers/preprocess.ts"],"mappings":";;;;;;YAKY,mBAAmB,OAAO,eAAe,QAAQ;;iBAG5C;;;;;EAKf;;;qBAIW,aAAa;;UAGhB;EACR,YAAY;IAAU;IAAgB;;EACtC,aAAa;EACb,aAAa;EACb,OAAO,eAAe;EACtB,WAAW;EACX,OAAO;IAAW;IAAe;MAAgC;EACjE,OAAO;EACP,YAAY,QAAQ;;KAEjB,gBAAgB,OAAO,WAAW;;;;;;;wBAQvB,uBAAuB,OAAO,cAAc,UAAS,oBAAyB;;;;;;wBA0BxE,oBAAoB,UAAS,oBAAyB,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preprocess.mjs","names":[],"sources":["../../src/drivers/preprocess.ts"],"sourcesContent":["/**\n * Transforms raw image bytes to improve OCR legibility. Returns the (possibly\n * unchanged) bytes — a preprocessor must never throw; on failure it returns the\n * input so recognition still runs.\n */\nexport type OcrPreprocessor = (image: Uint8Array) => Promise<Uint8Array>\n\n/** Tunables for the default {@link sharpPreprocessor}. */\nexport interface PreprocessOptions {\n /**\n * Upscale images narrower than this (px) to give the engine more pixels per\n * glyph — the single biggest win for the small OCR-B MRZ band. Default 1600.\n */\n minWidth?: number\n}\n\n/** A no-op preprocessor: passes the original bytes through unchanged. */\nexport const passthrough: OcrPreprocessor = async (image) => image\n\n/** Minimal structural type for the lazily-imported `sharp` module. */\ninterface SharpInstance {\n metadata(): Promise<{ width?: number; height?: number }>\n grayscale(): SharpInstance\n normalise(): SharpInstance\n median(size: number): SharpInstance\n sharpen(): SharpInstance\n resize(options: { width: number; withoutEnlargement: boolean }): SharpInstance\n png(): SharpInstance\n toBuffer(): Promise<Buffer>\n}\ntype SharpFactory = (input: Buffer) => SharpInstance\n\n/**\n * Build a preprocessor over an injected `sharp` factory: grayscale → contrast\n * normalise → light denoise → sharpen → upscale small images. This lifts faint\n * document text and the OCR-B MRZ band without the aggressive binarisation that\n * destroys detail under uneven lighting. Any failure falls back to the original.\n */\nexport function buildSharpPreprocessor(sharp: SharpFactory, options: PreprocessOptions = {}): OcrPreprocessor {\n const minWidth = options.minWidth ?? 1600\n return async (image) => {\n try {\n const input = Buffer.from(image)\n const base = sharp(input)\n const { width } = await base.metadata()\n let pipe = sharp(input).grayscale().normalise().median(1).sharpen()\n if (width && width < minWidth) {\n pipe = pipe.resize({ width: minWidth, withoutEnlargement: false })\n }\n const out = await pipe.png().toBuffer()\n return new Uint8Array(out)\n } catch {\n return image\n }\n }\n}\n\nlet cached: OcrPreprocessor | undefined\n\n/**\n * The default preprocessor, backed by the optional `sharp` package and resolved\n * once. If `sharp` isn't installed it degrades to {@link passthrough}, so OCR\n * still runs on the raw bytes (just without the legibility boost).\n */\nexport async function defaultPreprocessor(options: PreprocessOptions = {}): Promise<OcrPreprocessor> {\n if (cached) return cached\n const moduleName = 'sharp'\n try {\n const mod = (await import(/* @vite-ignore */ moduleName)) as unknown as { default: SharpFactory }\n cached = buildSharpPreprocessor(mod.default, options)\n } catch {\n cached = passthrough\n }\n return cached\n}\n"],"mappings":";;AAiBA,MAAa,cAA+B,OAAO,UAAU;;;;;;;AAqB7D,SAAgB,uBAAuB,OAAqB,UAA6B,CAAC,GAAoB;CAC5G,MAAM,WAAW,QAAQ,YAAY;CACrC,OAAO,OAAO,UAAU;EACtB,IAAI;GACF,MAAM,QAAQ,OAAO,KAAK,KAAK;GAE/B,MAAM,EAAE,UAAU,MADL,MAAM,KACQ,CAAC,CAAC,SAAS;GACtC,IAAI,OAAO,MAAM,KAAK,CAAC,CAAC,UAAU,CAAC,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ;GAClE,IAAI,SAAS,QAAQ,UACnB,OAAO,KAAK,OAAO;IAAE,OAAO;IAAU,oBAAoB;GAAM,CAAC;GAEnE,MAAM,MAAM,MAAM,KAAK,IAAI,CAAC,CAAC,SAAS;GACtC,OAAO,IAAI,WAAW,GAAG;EAC3B,QAAQ;GACN,OAAO;EACT;CACF;AACF;AAEA,IAAI;;;;;;AAOJ,eAAsB,oBAAoB,UAA6B,CAAC,GAA6B;CACnG,IAAI,QAAQ,OAAO;CACnB,MAAM,aAAa;CACnB,IAAI;EAEF,SAAS,wBAAuB,MADb;;GAA0B;
|
|
1
|
+
{"version":3,"file":"preprocess.mjs","names":[],"sources":["../../src/drivers/preprocess.ts"],"sourcesContent":["/**\n * Transforms raw image bytes to improve OCR legibility. Returns the (possibly\n * unchanged) bytes — a preprocessor must never throw; on failure it returns the\n * input so recognition still runs.\n */\nexport type OcrPreprocessor = (image: Uint8Array) => Promise<Uint8Array>\n\n/** Tunables for the default {@link sharpPreprocessor}. */\nexport interface PreprocessOptions {\n /**\n * Upscale images narrower than this (px) to give the engine more pixels per\n * glyph — the single biggest win for the small OCR-B MRZ band. Default 1600.\n */\n minWidth?: number\n}\n\n/** A no-op preprocessor: passes the original bytes through unchanged. */\nexport const passthrough: OcrPreprocessor = async (image) => image\n\n/** Minimal structural type for the lazily-imported `sharp` module. */\ninterface SharpInstance {\n metadata(): Promise<{ width?: number; height?: number }>\n grayscale(): SharpInstance\n normalise(): SharpInstance\n median(size: number): SharpInstance\n sharpen(): SharpInstance\n resize(options: { width: number; withoutEnlargement: boolean }): SharpInstance\n png(): SharpInstance\n toBuffer(): Promise<Buffer>\n}\ntype SharpFactory = (input: Buffer) => SharpInstance\n\n/**\n * Build a preprocessor over an injected `sharp` factory: grayscale → contrast\n * normalise → light denoise → sharpen → upscale small images. This lifts faint\n * document text and the OCR-B MRZ band without the aggressive binarisation that\n * destroys detail under uneven lighting. Any failure falls back to the original.\n */\nexport function buildSharpPreprocessor(sharp: SharpFactory, options: PreprocessOptions = {}): OcrPreprocessor {\n const minWidth = options.minWidth ?? 1600\n return async (image) => {\n try {\n const input = Buffer.from(image)\n const base = sharp(input)\n const { width } = await base.metadata()\n let pipe = sharp(input).grayscale().normalise().median(1).sharpen()\n if (width && width < minWidth) {\n pipe = pipe.resize({ width: minWidth, withoutEnlargement: false })\n }\n const out = await pipe.png().toBuffer()\n return new Uint8Array(out)\n } catch {\n return image\n }\n }\n}\n\nlet cached: OcrPreprocessor | undefined\n\n/**\n * The default preprocessor, backed by the optional `sharp` package and resolved\n * once. If `sharp` isn't installed it degrades to {@link passthrough}, so OCR\n * still runs on the raw bytes (just without the legibility boost).\n */\nexport async function defaultPreprocessor(options: PreprocessOptions = {}): Promise<OcrPreprocessor> {\n if (cached) return cached\n const moduleName = 'sharp'\n try {\n const mod = (await import(/* @vite-ignore */ moduleName)) as unknown as { default: SharpFactory }\n cached = buildSharpPreprocessor(mod.default, options)\n } catch {\n cached = passthrough\n }\n return cached\n}\n"],"mappings":";;AAiBA,MAAa,cAA+B,OAAO,UAAU;;;;;;;AAqB7D,SAAgB,uBAAuB,OAAqB,UAA6B,CAAC,GAAoB;CAC5G,MAAM,WAAW,QAAQ,YAAY;CACrC,OAAO,OAAO,UAAU;EACtB,IAAI;GACF,MAAM,QAAQ,OAAO,KAAK,KAAK;GAE/B,MAAM,EAAE,UAAU,MADL,MAAM,KACQ,CAAC,CAAC,SAAS;GACtC,IAAI,OAAO,MAAM,KAAK,CAAC,CAAC,UAAU,CAAC,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ;GAClE,IAAI,SAAS,QAAQ,UACnB,OAAO,KAAK,OAAO;IAAE,OAAO;IAAU,oBAAoB;GAAM,CAAC;GAEnE,MAAM,MAAM,MAAM,KAAK,IAAI,CAAC,CAAC,SAAS;GACtC,OAAO,IAAI,WAAW,GAAG;EAC3B,QAAQ;GACN,OAAO;EACT;CACF;AACF;AAEA,IAAI;;;;;;AAOJ,eAAsB,oBAAoB,UAA6B,CAAC,GAA6B;CACnG,IAAI,QAAQ,OAAO;CACnB,MAAM,aAAa;CACnB,IAAI;EAEF,SAAS,wBAAuB,MADb;;GAA0B;EACV,CAAC,SAAS,OAAO;CACtD,QAAQ;EACN,SAAS;CACX;CACA,OAAO;AACT"}
|
|
@@ -2,10 +2,9 @@ import { OcrDriver, OcrRequest } from "../types.mjs";
|
|
|
2
2
|
import { DocumentParserRegistry } from "../parsers/registry.mjs";
|
|
3
3
|
import { OcrPreprocessor } from "./preprocess.mjs";
|
|
4
4
|
import { OcrResultData } from "@arkyc/types";
|
|
5
|
-
|
|
6
5
|
//#region src/drivers/tesseract.d.ts
|
|
7
6
|
/** Options for a single recognition pass. */
|
|
8
|
-
interface RecognizeOptions {
|
|
7
|
+
export interface RecognizeOptions {
|
|
9
8
|
/**
|
|
10
9
|
* Constrain recognition to the {@link MRZ_CHARSET}. This forces ambiguous OCR-B
|
|
11
10
|
* glyphs into the machine-readable zone's alphabet (e.g. `O`→`0`, `I`→`1`),
|
|
@@ -14,11 +13,11 @@ interface RecognizeOptions {
|
|
|
14
13
|
mrz?: boolean;
|
|
15
14
|
}
|
|
16
15
|
/** Reads text from an image; returns text + an engine confidence in [0, 100]. */
|
|
17
|
-
type TesseractRecognize = (image: Uint8Array, language: string, options?: RecognizeOptions) => Promise<{
|
|
16
|
+
export type TesseractRecognize = (image: Uint8Array, language: string, options?: RecognizeOptions) => Promise<{
|
|
18
17
|
text: string;
|
|
19
18
|
confidence: number;
|
|
20
19
|
}>;
|
|
21
|
-
interface TesseractOcrOptions {
|
|
20
|
+
export interface TesseractOcrOptions {
|
|
22
21
|
/** Recognition language(s), default `eng`. */
|
|
23
22
|
language?: string;
|
|
24
23
|
/**
|
|
@@ -40,7 +39,7 @@ interface TesseractOcrOptions {
|
|
|
40
39
|
* runs it through the {@link DocumentParserRegistry} to extract structured fields.
|
|
41
40
|
* `tesseract.js` is imported lazily so it is only loaded when this driver runs.
|
|
42
41
|
*/
|
|
43
|
-
declare class TesseractOcrDriver implements OcrDriver {
|
|
42
|
+
export declare class TesseractOcrDriver implements OcrDriver {
|
|
44
43
|
readonly name = "tesseract";
|
|
45
44
|
private readonly language;
|
|
46
45
|
private readonly registry;
|
|
@@ -71,5 +70,4 @@ declare class TesseractOcrDriver implements OcrDriver {
|
|
|
71
70
|
private loadRecognizer;
|
|
72
71
|
}
|
|
73
72
|
//#endregion
|
|
74
|
-
export { RecognizeOptions, TesseractOcrDriver, TesseractOcrOptions, TesseractRecognize };
|
|
75
73
|
//# sourceMappingURL=tesseract.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tesseract.d.mts","names":[],"sources":["../../src/drivers/tesseract.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"tesseract.d.mts","names":[],"sources":["../../src/drivers/tesseract.ts"],"mappings":";;;;;;iBAeiB;;;;;;EAMf;;;YAIU,sBACV,OAAO,YACP,kBACA,UAAU,qBACP;EAAU;EAAc;;iBA0BZ;;EAEf;;;;;EAKA,WAAW;;EAEX,YAAY;;;;;;EAMZ,aAAa;;;;;;;qBAQF,8BAA8B;WAChC;mBACQ;mBACA;mBACA;mBACA;UACT;EAEI,YAAA,UAAS;EAOf,QAAQ,SAAS,aAAa,QAAQ;;UAoDpC;;UAYA;;;;;;;;;;UA2BA;;UAOM;;UAcA;;UASA"}
|
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { DocumentParser } from "./types.mjs";
|
|
2
|
-
|
|
3
2
|
//#region src/parsers/generic.d.ts
|
|
4
3
|
/** The generic best-effort text parser. */
|
|
5
|
-
declare function genericTextParser(): DocumentParser;
|
|
4
|
+
export declare function genericTextParser(): DocumentParser;
|
|
6
5
|
//#endregion
|
|
7
|
-
export { genericTextParser };
|
|
8
6
|
//# sourceMappingURL=generic.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generic.d.mts","names":[],"sources":["../../src/parsers/generic.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"generic.d.mts","names":[],"sources":["../../src/parsers/generic.ts"],"mappings":";;;wBA0FgB,qBAAqB"}
|
package/dist/parsers/mrz.d.mts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { DocumentParser } from "./types.mjs";
|
|
2
|
-
|
|
3
2
|
//#region src/parsers/mrz.d.ts
|
|
4
3
|
/** The MRZ parser — a country-agnostic default for machine-readable documents. */
|
|
5
|
-
declare function mrzParser(): DocumentParser;
|
|
4
|
+
export declare function mrzParser(): DocumentParser;
|
|
6
5
|
//#endregion
|
|
7
|
-
export { mrzParser };
|
|
8
6
|
//# sourceMappingURL=mrz.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mrz.d.mts","names":[],"sources":["../../src/parsers/mrz.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"mrz.d.mts","names":[],"sources":["../../src/parsers/mrz.ts"],"mappings":";;;wBAkKgB,aAAa"}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { DocumentParser, ParseInput, ParseOutput } from "./types.mjs";
|
|
2
2
|
import { DocumentType } from "@arkyc/types";
|
|
3
|
-
|
|
4
3
|
//#region src/parsers/registry.d.ts
|
|
5
4
|
/** Which stage of the pipeline produced a parse result. */
|
|
6
|
-
type ParseStage = 'mrz' | 'custom' | 'generic';
|
|
5
|
+
export type ParseStage = 'mrz' | 'custom' | 'generic';
|
|
7
6
|
/**
|
|
8
7
|
* A registry of document parsers, resolved in three stages for each document:
|
|
9
8
|
*
|
|
@@ -15,7 +14,7 @@ type ParseStage = 'mrz' | 'custom' | 'generic';
|
|
|
15
14
|
* Custom parsers declare the countries and document types they apply to; register
|
|
16
15
|
* one per document layout the MRZ + generic stages can't read.
|
|
17
16
|
*/
|
|
18
|
-
declare class DocumentParserRegistry {
|
|
17
|
+
export declare class DocumentParserRegistry {
|
|
19
18
|
private readonly primary;
|
|
20
19
|
private readonly fallback;
|
|
21
20
|
private readonly parsers;
|
|
@@ -45,10 +44,9 @@ declare class DocumentParserRegistry {
|
|
|
45
44
|
* parser as the fallback. Register country/document-type-specific custom parsers
|
|
46
45
|
* on top for documents the MRZ + generic stages can't read.
|
|
47
46
|
*/
|
|
48
|
-
declare function createDocumentParserRegistry(options?: {
|
|
47
|
+
export declare function createDocumentParserRegistry(options?: {
|
|
49
48
|
primary?: DocumentParser;
|
|
50
49
|
fallback?: DocumentParser;
|
|
51
50
|
}): DocumentParserRegistry;
|
|
52
51
|
//#endregion
|
|
53
|
-
export { DocumentParserRegistry, ParseStage, createDocumentParserRegistry };
|
|
54
52
|
//# sourceMappingURL=registry.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.d.mts","names":[],"sources":["../../src/parsers/registry.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"registry.d.mts","names":[],"sources":["../../src/parsers/registry.ts"],"mappings":";;;;YA0BY;;;;;;;;;;;;qBAaC;mBAQQ;mBACA;mBARF;;;;;EAOE,YAAA,SAAS,gBACT,UAAU;;EAI7B,SAAS,QAAQ;;EAMjB,WAAW,yBAAyB,eAAe,sBAAsB;;;;;UAYjE;;;;;;EAcR,MAAM,OAAO,aAAa;;;;;;;wBAmCZ,6BACd;EAAW,UAAU;EAAgB,WAAW;IAC/C"}
|
package/dist/parsers/types.d.mts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { DocumentType, OcrFields } from "@arkyc/types";
|
|
2
|
-
|
|
3
2
|
//#region src/parsers/types.d.ts
|
|
4
3
|
/** The OCR text + context handed to a document parser. */
|
|
5
|
-
interface ParseInput {
|
|
4
|
+
export interface ParseInput {
|
|
6
5
|
/** Full OCR text for the document (raw engine output). */
|
|
7
6
|
text: string;
|
|
8
7
|
/** Pre-split lines; derived from `text` when omitted. */
|
|
@@ -13,7 +12,7 @@ interface ParseInput {
|
|
|
13
12
|
country?: string | null;
|
|
14
13
|
}
|
|
15
14
|
/** A parser's structured result. */
|
|
16
|
-
interface ParseOutput {
|
|
15
|
+
export interface ParseOutput {
|
|
17
16
|
fields: OcrFields;
|
|
18
17
|
/** Confidence in this parse, 0–1. */
|
|
19
18
|
confidence: number;
|
|
@@ -26,7 +25,7 @@ interface ParseOutput {
|
|
|
26
25
|
* those against the user's selection to pick the most specific parser, and falls
|
|
27
26
|
* back to the default when none match (or none can parse the text).
|
|
28
27
|
*/
|
|
29
|
-
interface DocumentParser {
|
|
28
|
+
export interface DocumentParser {
|
|
30
29
|
readonly name: string;
|
|
31
30
|
/**
|
|
32
31
|
* ISO-3166 country codes (alpha-2 or alpha-3) this parser applies to. Omit (or
|
|
@@ -39,5 +38,4 @@ interface DocumentParser {
|
|
|
39
38
|
parse(input: ParseInput): ParseOutput | null;
|
|
40
39
|
}
|
|
41
40
|
//#endregion
|
|
42
|
-
export { DocumentParser, ParseInput, ParseOutput };
|
|
43
41
|
//# sourceMappingURL=types.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../../src/parsers/types.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../../src/parsers/types.ts"],"mappings":";;;iBAGiB;;EAEf;;EAEA;;EAEA,eAAe;;EAEf;;;iBAIe;EACf,QAAQ;;EAER;;EAEA;;;;;;;;iBASe;WACN;;;;;WAKA;;WAEA,yBAAyB;;EAElC,MAAM,OAAO,aAAa"}
|
package/dist/registry.d.mts
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { OcrConfig, OcrDriver } from "./types.mjs";
|
|
2
|
-
|
|
3
2
|
//#region src/registry.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* Selects an OCR driver from config. Call sites depend only on the
|
|
6
5
|
* {@link OcrDriver} interface, so swapping `config.driver` changes behaviour
|
|
7
6
|
* with no other changes.
|
|
8
7
|
*/
|
|
9
|
-
declare class OcrDriverFactory {
|
|
8
|
+
export declare class OcrDriverFactory {
|
|
10
9
|
/**
|
|
11
10
|
* Resolve the OCR driver named by `config`.
|
|
12
11
|
*
|
|
@@ -16,5 +15,4 @@ declare class OcrDriverFactory {
|
|
|
16
15
|
static create(config: OcrConfig): OcrDriver;
|
|
17
16
|
}
|
|
18
17
|
//#endregion
|
|
19
|
-
export { OcrDriverFactory };
|
|
20
18
|
//# sourceMappingURL=registry.d.mts.map
|
package/dist/registry.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.d.mts","names":[],"sources":["../src/registry.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"registry.d.mts","names":[],"sources":["../src/registry.ts"],"mappings":";;;;;;;qBAYa;;;;;;;SAOJ,OAAO,QAAQ,YAAY"}
|
package/dist/types.d.mts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { AiOcrProvider } from "./drivers/ai.mjs";
|
|
2
2
|
import { DocumentType, OcrResultData } from "@arkyc/types";
|
|
3
|
-
|
|
4
3
|
//#region src/types.d.ts
|
|
5
4
|
/** The bytes + context handed to an OCR driver for extraction. */
|
|
6
|
-
interface OcrRequest {
|
|
5
|
+
export interface OcrRequest {
|
|
7
6
|
/** Raw document-front image bytes. */
|
|
8
7
|
image: Uint8Array;
|
|
9
8
|
/**
|
|
@@ -28,14 +27,14 @@ interface OcrRequest {
|
|
|
28
27
|
};
|
|
29
28
|
}
|
|
30
29
|
/** A pluggable OCR provider. */
|
|
31
|
-
interface OcrDriver {
|
|
30
|
+
export interface OcrDriver {
|
|
32
31
|
readonly name: string;
|
|
33
32
|
extract(request: OcrRequest): Promise<OcrResultData>;
|
|
34
33
|
}
|
|
35
34
|
/** Identifier for a registered OCR driver. */
|
|
36
|
-
type OcrDriverName = 'mock' | 'tesseract' | 'external' | 'ai';
|
|
35
|
+
export type OcrDriverName = 'mock' | 'tesseract' | 'external' | 'ai';
|
|
37
36
|
/** Configuration selecting + parameterising the active OCR driver. */
|
|
38
|
-
interface OcrConfig {
|
|
37
|
+
export interface OcrConfig {
|
|
39
38
|
driver: OcrDriverName;
|
|
40
39
|
/** Base URL for the `external` driver, or API base override for `ai`. */
|
|
41
40
|
endpoint?: string;
|
|
@@ -52,5 +51,4 @@ interface OcrConfig {
|
|
|
52
51
|
maxEdge?: number;
|
|
53
52
|
}
|
|
54
53
|
//#endregion
|
|
55
|
-
export { OcrConfig, OcrDriver, OcrDriverName, OcrRequest };
|
|
56
54
|
//# sourceMappingURL=types.d.mts.map
|
package/dist/types.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";;;;iBAIiB;;EAEf,OAAO;;;;;EAKP,YAAY;;EAEZ,eAAe;;EAEf;;;;;EAKA;IACE;IACA;IACA;IACA;IACA;;;;iBAKa;WACN;EACT,QAAQ,SAAS,aAAa,QAAQ;;;YAI5B;;iBAGK;EACf,QAAQ;;EAER;EACA;;EAEA;;EAEA,aAAa;;EAEb;;EAEA;;EAEA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arkyc/ocr",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.1",
|
|
4
4
|
"description": "Driver-based OCR extraction",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"dist"
|
|
38
38
|
],
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@arkyc/types": "^2.
|
|
40
|
+
"@arkyc/types": "^2.1.1"
|
|
41
41
|
},
|
|
42
42
|
"optionalDependencies": {
|
|
43
43
|
"sharp": "^0.33.5",
|