Provides the TypeScript client library for the Mistral AI API.
Downloads / mo 27.0M
Stars 161
Last release 3.5.0
License Apache-2.0 $ npm install @mistralai/mistralai Copy
import { Mistral } from '@mistralai/mistralai';
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
const result = await client.ocr.process({ model: 'mistral-ocr-latest', document: { type: 'document_url', documentUrl: 'https://arxiv.org/pdf/2201.04234' } });
console.log(result.pages[0]?.markdown);
@mistralai/mistralai examples From open-source projects on GitHub async ocr(imagePath: string) {
try {
const start = performance.now();
const response = await this.client.ocr.process({
model: 'mistral-ocr-latest',
document: {
imageUrl: imagePath,
},
includeImageBase64: true,
});
const text = response.pages.map((page) => page.markdown).join('\n');
const end = performance.now();
const imageBase64s = response.pages.flatMap((page) =>
page.images.map((image) => image.imageBase64).filter((base64) => base64),
);
return {
text,
imageBase64s,
usage: {
duration: end - start,
totalCost: COST_PER_IMAGE,
},
};
} catch (error) {
console.error('Mistral OCR Error:', error);
throw error;
}
}
Show full example Runs the Tesseract OCR engine in browsers and Node.js through WebAssembly.
Downloads / mo 22.2M
Stars 38.8K
Last release 7.0.0
License Apache-2.0 Strengths Reuses initialized OCR workers . Reuse a worker for multiple images before terminating it. Restricts recognized characters . Set tessedit_char_whitelist when only specified characters are valid. Limitations PDF input needs image rendering . Render PDF pages as images before passing them to Tesseract.js. Structured output needs explicit enabling . Enable blocks or hocr when downstream code needs document layout. $ npm install tesseract.js Copy
import { createWorker } from 'tesseract.js';
(async () => {
const worker = await createWorker('eng');
const ret = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png');
console.log(ret.data.text);
await worker.terminate();
})();
tesseract.js examples From open-source projects on GitHub function recognizeWithTimeout(
worker: Tesseract.Worker,
canvas: HTMLCanvasElement,
timeoutMs: number
): Promise<Tesseract.RecognizeResult> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
const error = new Error(
trText('OCR recognize timed out after {{timeoutMs}}ms', { timeoutMs })
);
error.name = 'OcrTimeoutError';
reject(error);
}, timeoutMs);
worker
.recognize(canvas, {}, { text: true, hocr: true })
.then((result) => {
clearTimeout(timer);
resolve(result);
})
.catch((err) => {
clearTimeout(timer);
reject(err);
});
});
}
Show full example Provides the Google Cloud Vision API client for Node.js.
Downloads / mo 3.5M
Stars 3.2K
Last release 6.2.0
License Apache-2.0 $ npm install @google-cloud/vision Copy
const { ImageAnnotatorClient } = require('@google-cloud/vision');
(async () => {
const client = new ImageAnnotatorClient();
const [result] = await client.textDetection('./image.png');
console.log(result.textAnnotations?.[0]?.description ?? '');
})();
Google Cloud Vision examples From open-source projects on GitHub async function detectFulltext(fileName) {
// [START vision_fulltext_detection]
// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
/**
* TODO(developer): Uncomment the following line before running the sample.
*/
// const fileName = 'Local image file, e.g. /path/to/image.png';
// Read a local image as a text document
const [result] = await client.documentTextDetection(fileName);
const fullTextAnnotation = result.fullTextAnnotation;
console.log(`Full text: ${fullTextAnnotation.text}`);
fullTextAnnotation.pages.forEach(page => {
page.blocks.forEach(block => {
console.log(`Block confidence: ${block.confidence}`);
block.paragraphs.forEach(paragraph => {
console.log(`Paragraph confidence: ${paragraph.confidence}`);
paragraph.words.forEach(word => {
const wordText = word.symbols.map(s => s.text).join('');
console.log(`Word text: ${wordText}`);
console.log(`Word confidence: ${word.confidence}`);
word.symbols.forEach(symbol => {
console.log(`Symbol text: ${symbol.text}`);
console.log(`Symbol confidence: ${symbol.confidence}`);
});
});
});
});
});
// [END vision_fulltext_detection]
}
Show full example Provides the Document AI client for Node.js.
Downloads / mo 2.5M
Stars 3.2K
Last release 10.2.0
License Apache-2.0 $ npm install @google-cloud/documentai Copy
const { DocumentProcessorServiceClient } = require('@google-cloud/documentai');
const { readFile } = require('node:fs/promises');
(async () => {
const client = new DocumentProcessorServiceClient();
const [result] = await client.processDocument({ name: process.env.DOCUMENT_AI_PROCESSOR, rawDocument: { content: (await readFile('./document.pdf')).toString('base64'), mimeType: 'application/pdf' } });
console.log(result.document?.text);
})();
@google-cloud/documentai examples From open-source projects on GitHub async ocr(imagePath: string) {
try {
// Download the image
const response = await fetch(imagePath);
const arrayBuffer = await response.arrayBuffer();
const imageContent = Buffer.from(arrayBuffer).toString('base64');
// Determine MIME type from URL
const mimeType = this.getMimeType(imagePath);
const request = {
name: this.processorPath,
rawDocument: {
content: imageContent,
mimeType: mimeType,
},
};
const start = performance.now();
const [result] = await this.client.processDocument(request);
const { document } = result;
const end = performance.now();
// Extract text from the document
const text = document?.text || '';
return {
text,
usage: {
duration: end - start,
totalCost: COST_PER_PAGE, // the input is always 1 page.
},
};
} catch (error) {
console.error('Google Document AI Error:', error);
throw error;
}
}
Show full example Calls Document Intelligence to extract document content, layout, and structured data.
Downloads / mo 1.5M
Stars 2.3K
Last release 1.1.0
License MIT Strengths Extracts layout alongside text . Use prebuilt-layout to retrieve text and document structure. Returns formatted document content . Request Markdown output when downstream code needs document formatting. Limitations Requires an OCR service . Connect to a Document Intelligence endpoint rather than an embedded OCR engine. Searchable PDF requires prebuilt-read . Use PDF input with prebuilt-read for searchable PDF output. $ npm install @azure-rest/ai-document-intelligence Copy
import DocumentIntelligence, { isUnexpected, getLongRunningPoller, type AnalyzeOperationOutput } from '@azure-rest/ai-document-intelligence';
import { readFile } from 'node:fs/promises';
const client = DocumentIntelligence(process.env.DOCUMENT_INTELLIGENCE_ENDPOINT!, { key: process.env.DOCUMENT_INTELLIGENCE_API_KEY! });
const response = await client.path('/documentModels/{modelId}:analyze', 'prebuilt-layout').post({ contentType: 'application/json', body: { base64Source: await readFile('./document.pdf', { encoding: 'base64' }) } });
if (isUnexpected(response)) throw response.body.error;
const result = (await getLongRunningPoller(client, response).pollUntilDone()).body as AnalyzeOperationOutput;
console.log(result.analyzeResult?.content);
@azure-rest/ai-document-intelligence examples From open-source projects on GitHub async ocr(imagePath: string) {
try {
const start = performance.now();
const initialResponse = await this.client
.path('/documentModels/{modelId}:analyze', 'prebuilt-layout')
.post({
contentType: 'application/json',
body: {
urlSource: imagePath,
},
queryParameters: { outputContentFormat: 'markdown' },
});
if (isUnexpected(initialResponse)) {
throw initialResponse.body.error;
}
const poller = getLongRunningPoller(this.client, initialResponse);
const result = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;
const analyzeResult = result.analyzeResult;
const text = analyzeResult?.content;
const end = performance.now();
return {
text,
usage: {
duration: end - start,
totalCost: COST_PER_PAGE, // the input is always 1 page.
},
};
} catch (error) {
console.error('Azure Document Intelligence Error:', error);
throw error;
}
}
Show full example Provides the official TypeScript library for the Llama Cloud API.
Downloads / mo 758.4K
Stars 36
Last release 2.19.0
License MIT $ npm install @llamaindex/llama-cloud Copy
import LlamaCloud from '@llamaindex/llama-cloud';
const client = new LlamaCloud();
const result = await client.parsing.parse({ tier: 'cost_effective', version: 'latest', source_url: 'https://arxiv.org/pdf/2201.04234', expand: ['markdown'] });
console.log(result.markdown);
Wraps the Tesseract OCR engine for Node.js.
Downloads / mo 208.0K
Stars 320
Last release 2.2.1
License MIT $ npm install node-tesseract-ocr Copy
const tesseract = require('node-tesseract-ocr');
tesseract.recognize('./image.png', { lang: 'eng' }).then(console.log).catch(console.error);