@arkyc/ocr 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/drivers/ai.d.mts +2 -0
- package/dist/drivers/ai.d.mts.map +1 -1
- package/dist/drivers/ai.mjs +25 -10
- package/dist/drivers/ai.mjs.map +1 -1
- package/dist/registry.mjs +3 -1
- package/dist/registry.mjs.map +1 -1
- package/dist/types.d.mts +4 -0
- package/dist/types.d.mts.map +1 -1
- package/package.json +2 -2
package/dist/drivers/ai.d.mts
CHANGED
|
@@ -30,6 +30,8 @@ export interface AiExtraction {
|
|
|
30
30
|
documentType?: DocumentType | null;
|
|
31
31
|
/** Best-effort tamper/replay read; omitted when the model reported nothing. */
|
|
32
32
|
authenticity?: OcrAuthenticity;
|
|
33
|
+
/** The model's own tool-call arguments, kept for debugging what it actually returned. */
|
|
34
|
+
modelOutput?: Record<string, unknown>;
|
|
33
35
|
}
|
|
34
36
|
/**
|
|
35
37
|
* Calls a vision model and returns the raw extracted fields. Injected so the
|
|
@@ -1 +1 @@
|
|
|
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;;;;;;;
|
|
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
|
}
|
|
@@ -195,7 +196,7 @@ const READ_TOOL = {
|
|
|
195
196
|
},
|
|
196
197
|
documentNumber: {
|
|
197
198
|
type: "string",
|
|
198
|
-
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)."
|
|
199
200
|
},
|
|
200
201
|
issueDate: {
|
|
201
202
|
type: "string",
|
|
@@ -439,17 +440,31 @@ function workersAiVision(opts) {
|
|
|
439
440
|
* @returns
|
|
440
441
|
*/
|
|
441
442
|
function mapToolInput(input) {
|
|
442
|
-
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
|
+
};
|
|
443
457
|
const docType = str(input.documentType);
|
|
444
458
|
return {
|
|
459
|
+
modelOutput: input,
|
|
445
460
|
fields: {
|
|
446
|
-
firstName:
|
|
447
|
-
lastName:
|
|
448
|
-
fullName:
|
|
449
|
-
dateOfBirth:
|
|
450
|
-
documentNumber:
|
|
451
|
-
expiryDate:
|
|
452
|
-
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")
|
|
453
468
|
},
|
|
454
469
|
legibility: typeof input.legibility === "number" ? input.legibility : void 0,
|
|
455
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,mB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H;;;;;;;AAQA,SAAS,gBAAgB,OAA+C;CACtE,IAAI,MAAM,OAAO,OAAQ,MAAM,OAAO,KAAM,OAAO;CACnD,IAAI,MAAM,OAAO,OAAQ,MAAM,OAAO,IAAM,OAAO;CACnD,IAAI,MAAM,OAAO,MAAQ,MAAM,OAAO,MAAQ,MAAM,OAAO,IAAM,OAAO;CACxE,OAAO;AACT;AAUA,IAAI;;AAGJ,eAAe,YAA0C;CACvD,IAAI,iBAAiB,KAAA,GAAW,OAAO;CACvC,MAAM,aAAa;CACnB,IAAI;EAEF,gBAAe,MADI;;GAA0B;EAC3B,CAAC;CACrB,QAAQ;EACN,eAAe;CACjB;CACA,OAAO;AACT;;;;;;;;;;;;AAaA,eAAe,aAAa,OAAmB,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
|
+
{"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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rDriverFactory = class {
|
|
|
26
26
|
apiKey: config.apiKey,
|
|
27
27
|
model: config.model,
|
|
28
28
|
baseUrl: config.endpoint,
|
|
29
|
-
maxEdge: config.maxEdge
|
|
29
|
+
maxEdge: config.maxEdge,
|
|
30
|
+
timeoutMs: config.timeoutMs,
|
|
31
|
+
maxRetries: config.maxRetries
|
|
30
32
|
});
|
|
31
33
|
default: throw new Error(`Unknown OCR driver: ${config.driver}`);
|
|
32
34
|
}
|
package/dist/registry.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.mjs","names":[],"sources":["../src/registry.ts"],"sourcesContent":["import type { OcrConfig, OcrDriver } from './types'\n\nimport { AnthropicOcrDriver } from './drivers/ai'\nimport { ExternalOcrDriver } from './drivers/external'\nimport { MockOcrDriver } from './drivers/mock'\nimport { TesseractOcrDriver } from './drivers/tesseract'\n\n/**\n * Selects an OCR driver from config. Call sites depend only on the\n * {@link OcrDriver} interface, so swapping `config.driver` changes behaviour\n * with no other changes.\n */\nexport class OcrDriverFactory {\n /**\n * Resolve the OCR driver named by `config`.\n *\n * @param config\n * @returns\n */\n static create(config: OcrConfig): OcrDriver {\n switch (config.driver) {\n case 'mock':\n return new MockOcrDriver()\n case 'tesseract':\n return new TesseractOcrDriver({ language: config.language })\n case 'external':\n return new ExternalOcrDriver(config)\n case 'ai':\n return new AnthropicOcrDriver({\n provider: config.aiProvider,\n accountId: config.accountId,\n apiKey: config.apiKey,\n model: config.model,\n baseUrl: config.endpoint,\n maxEdge: config.maxEdge,\n })\n default:\n throw new Error(`Unknown OCR driver: ${(config as OcrConfig).driver}`)\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,mBAAb,MAA8B;;;;;;;CAO5B,OAAO,OAAO,QAA8B;EAC1C,QAAQ,OAAO,QAAf;GACE,KAAK,QACH,OAAO,IAAI,cAAc;GAC3B,KAAK,aACH,OAAO,IAAI,mBAAmB,EAAE,UAAU,OAAO,SAAS,CAAC;GAC7D,KAAK,YACH,OAAO,IAAI,kBAAkB,MAAM;GACrC,KAAK,MACH,OAAO,IAAI,mBAAmB;IAC5B,UAAU,OAAO;IACjB,WAAW,OAAO;IAClB,QAAQ,OAAO;IACf,OAAO,OAAO;IACd,SAAS,OAAO;IAChB,SAAS,OAAO;
|
|
1
|
+
{"version":3,"file":"registry.mjs","names":[],"sources":["../src/registry.ts"],"sourcesContent":["import type { OcrConfig, OcrDriver } from './types'\n\nimport { AnthropicOcrDriver } from './drivers/ai'\nimport { ExternalOcrDriver } from './drivers/external'\nimport { MockOcrDriver } from './drivers/mock'\nimport { TesseractOcrDriver } from './drivers/tesseract'\n\n/**\n * Selects an OCR driver from config. Call sites depend only on the\n * {@link OcrDriver} interface, so swapping `config.driver` changes behaviour\n * with no other changes.\n */\nexport class OcrDriverFactory {\n /**\n * Resolve the OCR driver named by `config`.\n *\n * @param config\n * @returns\n */\n static create(config: OcrConfig): OcrDriver {\n switch (config.driver) {\n case 'mock':\n return new MockOcrDriver()\n case 'tesseract':\n return new TesseractOcrDriver({ language: config.language })\n case 'external':\n return new ExternalOcrDriver(config)\n case 'ai':\n return new AnthropicOcrDriver({\n provider: config.aiProvider,\n accountId: config.accountId,\n apiKey: config.apiKey,\n model: config.model,\n baseUrl: config.endpoint,\n maxEdge: config.maxEdge,\n timeoutMs: config.timeoutMs,\n maxRetries: config.maxRetries,\n })\n default:\n throw new Error(`Unknown OCR driver: ${(config as OcrConfig).driver}`)\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,mBAAb,MAA8B;;;;;;;CAO5B,OAAO,OAAO,QAA8B;EAC1C,QAAQ,OAAO,QAAf;GACE,KAAK,QACH,OAAO,IAAI,cAAc;GAC3B,KAAK,aACH,OAAO,IAAI,mBAAmB,EAAE,UAAU,OAAO,SAAS,CAAC;GAC7D,KAAK,YACH,OAAO,IAAI,kBAAkB,MAAM;GACrC,KAAK,MACH,OAAO,IAAI,mBAAmB;IAC5B,UAAU,OAAO;IACjB,WAAW,OAAO;IAClB,QAAQ,OAAO;IACf,OAAO,OAAO;IACd,SAAS,OAAO;IAChB,SAAS,OAAO;IAChB,WAAW,OAAO;IAClB,YAAY,OAAO;GACrB,CAAC;GACH,SACE,MAAM,IAAI,MAAM,uBAAwB,OAAqB,QAAQ;EACzE;CACF;AACF"}
|
package/dist/types.d.mts
CHANGED
|
@@ -49,6 +49,10 @@ export interface OcrConfig {
|
|
|
49
49
|
model?: string;
|
|
50
50
|
/** Longest image edge (px) uploaded by the `ai` driver. */
|
|
51
51
|
maxEdge?: number;
|
|
52
|
+
/** Per-attempt request timeout (ms) for the `ai` driver; large vision models may need more. */
|
|
53
|
+
timeoutMs?: number;
|
|
54
|
+
/** Retries after a timeout, network error or 429/529 for the `ai` driver. */
|
|
55
|
+
maxRetries?: number;
|
|
52
56
|
}
|
|
53
57
|
//#endregion
|
|
54
58
|
//# 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":";;;;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"}
|
|
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;;EAEA;;EAEA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arkyc/ocr",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
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.2.0"
|
|
41
41
|
},
|
|
42
42
|
"optionalDependencies": {
|
|
43
43
|
"sharp": "^0.33.5",
|