SmartOCR is a powerful OCR (Optical Character Recognition) module designed for text extraction and interaction from ALL file types. It enables you to extract text from images, PDFs, documents, spreadsheets, and more, with intelligent link detection and clickable link generation.
- π Universal File Support: Extract text from images, PDFs, DOCX, Excel, CSV, HTML, RTF, Markdown, and more
- π Smart Link Detection: Automatically detect URLs, email addresses, and file paths in extracted text
- π±οΈ Clickable Links: Convert detected links to clickable HTML with proper formatting
- β‘ High Performance: Internal singleton worker pattern, batch processing, and memory-efficient streaming
- π― MIME Type Detection: Automatic file type recognition and appropriate extraction method
- π Batch Processing: Process multiple files simultaneously for maximum efficiency
- π Functional API: Simple function calls - no classes or instances needed!
- π― One Function Rule: Use
extractText()for ANY file type - no need to remember different function names! - π€ WebdriverIO Integration: Built-in OCR functions for automated testing and web scraping
- π Link Persistence: Save and load extracted links to/from JSON files
- π Structured Data Extraction: Extract structured data from specific document types
- π Oxford Test Support: Specialized extraction for Oxford Test documents
| Category | Formats | Extractor |
|---|---|---|
| Images | JPEG, PNG, GIF, BMP, TIFF, WebP | OCR (Tesseract.js) |
| Documents | PDF Parser | |
| Word Processing | DOCX, RTF | Mammoth.js + Custom |
| Spreadsheets | XLSX, XLS | Excel.js |
| Data Files | CSV | CSV Parser |
| Web Files | HTML | HTML Parser |
| Text Files | TXT, MD | Direct Read |
Install SmartOCR via pnpm:
pnpm add klassijs-smart-ocrconst { extractText } = require('klassijs-smart-ocr');
// Extract text from ANY supported file type - just call extractText!
const result = await extractText('./document.pdf'); // PDF
const result2 = await extractText('./image.jpg'); // Image
const result3 = await extractText('./spreadsheet.xlsx'); // Excel
const result4 = await extractText('./document.docx'); // Word
const result5 = await extractText('./data.csv'); // CSV
const result6 = await extractText('./webpage.html'); // HTML
// All return the same structure:
console.log('Extracted Text:', result.text);
console.log('Links Found:', result.links);
console.log('File Type:', result.mimeType);const { extractText, makeLinksClickable } = require('klassijs-smart-ocr');
// Extract text and links from any file
const result = await extractText('./webpage.html');
// Convert links to clickable HTML
const clickableText = makeLinksClickable(result.text, result.links);
console.log(clickableText);const { batchExtract } = require('klassijs-smart-ocr');
// Process multiple files of different types efficiently
const files = ['./image.jpg', './document.pdf', './spreadsheet.xlsx'];
const results = await batchExtract(files);
results.forEach(result => {
if (result.error) {
console.log(`Failed: ${result.filePath} - ${result.error}`);
} else {
console.log(`Success: ${result.filePath} - ${result.links.length} links`);
}
});Universal text extraction for ALL file types - automatically detects file type and uses appropriate extractor.
- Parameters:
filePath(string) - Path to any supported fileoptions(object, optional) - Additional options for extraction
- Returns: Promise with
{ text, mimeType, links, filePath } - Supported: Images, PDFs, DOCX, Excel, CSV, HTML, RTF, TXT, MD, and more!
- Parameters:
text(string) - Text to analyze - Returns: Array of detected links (URLs, emails, file paths)
- Parameters:
text(string) - Original textlinks(array) - Array of detected links
- Returns: HTML string with clickable links
- Parameters:
filePaths(array) - Array of file paths - Returns: Promise of results
- Parameters:
links(array) - Array of links to savefilePath(string) - Original file path (used for naming)outputDir(string, optional) - Output directory for JSON files
- Returns: Promise - Path to saved JSON file
- Parameters:
searchTerm(string) - Search term to find relevant JSON filestestStage(string) - Test stage identifieroutputDir(string, optional) - Directory to search for JSON files
- Returns: Promise - Array of loaded links
- Parameters:
filePath(string) - Path to the documentoptions(object, optional) - Extraction options
- Returns: Promise - Structured data object
Extracts text from an image using OCR.
- Parameters:
imagePath(string) - Path to image fileoptions(object, optional) - OCR options
- Returns: Promise - Extracted text
Finds the position of text within an image.
- Parameters:
imagePath(string) - Path to image filesearchText(string) - Text to search foroptions(object, optional) - Search options
- Returns: Promise - Position coordinates
Waits for specific text to appear in an image.
- Parameters:
imagePath(string) - Path to image filesearchText(string) - Text to wait fortimeout(number, optional) - Timeout in millisecondsoptions(object, optional) - Wait options
- Returns: Promise - True if text found within timeout
Simulates clicking on text within an image.
- Parameters:
imagePath(string) - Path to image filesearchText(string) - Text to click onoptions(object, optional) - Click options
- Returns: Promise - Click result
Sets a value in an input field identified by nearby text.
- Parameters:
imagePath(string) - Path to image filesearchText(string) - Text near the input fieldvalue(string) - Value to setoptions(object, optional) - Set value options
- Returns: Promise - Success status
Performs multiple OCR operations in sequence.
- Parameters:
imagePath(string) - Path to image fileoperations(array) - Array of operations to performoptions(object, optional) - Batch options
- Returns: Promise - Results of all operations
Performs fuzzy text matching with configurable threshold.
- Parameters:
text(string) - Text to search insearchTerm(string) - Term to search forthreshold(number, optional) - Similarity threshold (0-1)
- Returns: boolean - True if match found
Finds the position of text within a larger text block.
- Parameters:
text(string) - Text to search insearchTerm(string) - Term to search for
- Returns: object - Position information
Waits for text to appear in a string.
- Parameters:
text(string) - Text to monitorsearchTerm(string) - Text to wait fortimeout(number, optional) - Timeout in milliseconds
- Returns: Promise - True if text found
Extracts structured data specifically from Oxford Test documents.
- Parameters:
filePath(string) - Path to Oxford Test document - Returns: Promise - Structured test data including scores, dates, and overall CEFR level
const { extractText, extractLinks } = require('klassijs-smart-ocr'); // Process any file type with the same function const fileTypes = [ './document.pdf', './image.jpg', './spreadsheet.xlsx', './webpage.html', './data.csv' ]; for (const file of fileTypes) { try { const result = await extractText(file); console.log(`${file}: ${result.mimeType} - ${result.links.length} links found`); } catch (error) { console.log(`${file}: Error - ${error.message}`); } }
const { extractText, saveLinksToJson, loadLinksFromJson } = require('klassijs-smart-ocr'); // Extract and save links const result = await extractText('./document.pdf'); if (result.links.length > 0) { const savedPath = await saveLinksToJson(result.links, './document.pdf'); console.log(`Links saved to: ${savedPath}`); } // Load previously saved links const loadedLinks = await loadLinksFromJson('document', 'test-stage'); console.log(`Loaded ${loadedLinks.length} links`);
const { ocrGetText, ocrClickOnText, ocrSetValue } = require('klassijs-smart-ocr'); // Extract text from a screenshot const text = await ocrGetText('./screenshot.png'); console.log('Page text:', text); // Click on a button by text await ocrClickOnText('./screenshot.png', 'Submit'); // Fill a form field await ocrSetValue('./screenshot.png', 'Username:', 'testuser');
const { extractStructuredData, extractOxfordTestStructuredData } = require('klassijs-smart-ocr'); // Extract structured data from any document const data = await extractStructuredData('./document.pdf'); console.log('Structured data:', data); // Extract Oxford Test specific data const oxfordData = await extractOxfordTestStructuredData('./oxford-test.pdf'); console.log('Overall CEFR Level:', oxfordData.overallResults.cefrLevel); console.log('Overall Score:', oxfordData.overallResults.score);
const { ocrBatchOperations } = require('klassijs-smart-ocr'); // Perform multiple OCR operations const operations = [ { type: 'getText', searchText: 'Welcome' }, { type: 'click', searchText: 'Login' }, { type: 'setValue', searchText: 'Username:', value: 'user123' } ]; const results = await ocrBatchOperations('./screenshot.png', operations); console.log('Batch results:', results);
const { extractText, extractLinks } = require('klassijs-smart-ocr'); // Extract text from any document const result = await extractText('./complex-document.docx'); // Analyze links found result.links.forEach(link => { if (link.includes('@')) { console.log('Email found:', link); } else if (link.startsWith('http')) { console.log('URL found:', link); } else if (link.startsWith('/')) { console.log('File path found:', link); } });
const { extractText } = require('klassijs-smart-ocr'); const files = ['./image.jpg', './document.pdf', './unknown.xyz']; files.forEach(async (file) => { try { const result = await extractText(file); console.log(`${file} is supported and processed successfully`); } catch (error) { console.log(`${file} is not supported or failed to process`); } });
const { batchExtract } = require('klassijs-smart-ocr'); // Process multiple files of different types const results = await batchExtract(['./file1.pdf', './file2.docx', './file3.jpg']); console.log('All files processed successfully');
- Internal Singleton Worker: OCR worker is created once and reused internally
- Memory Efficient: Streaming for large files (CSV, etc.)
- Parallel Processing: Batch operations use Promise.all
- Smart Caching: MIME type detection is cached
- Automatic Resource Management: Resources are managed internally - no user cleanup needed!
- No Instance Creation: Users just call functions - no overhead!
- Universal Function: One
extractText()function handles ALL file types! - Link Persistence: Save and reload extracted links without reprocessing
- Structured Data: Extract meaningful data structures from documents
- WebdriverIO Ready: Built-in functions for automated testing workflows
The system automatically detects:
- URLs:
https://example.com,http://localhost:3000 - Email Addresses:
user@domain.com,contact+tag@company.co.uk - File Paths:
/downloads/file.pdf,./relative/path.txt - Relative URLs:
../parent/directory,./current/file
SmartOCR includes specialized support for Oxford Test documents:
- Automatic Score Extraction: Reading, Writing, Speaking, and Listening scores
- Overall CEFR Level Detection: Automatic overall CEFR level identification (A1-C2)
- Date Extraction: Test and certificate dates
- Structured Output: Clean, organized data structure for test results
Contributions are welcome! If you have ideas for improvements or new features, feel free to open an issue or submit a pull request.
- Fork the repository
- Create a new branch
- Make your changes and commit them
- Submit a pull request
SmartOCR is open-source software licensed under the MIT License.
Special thanks to the developers of:
tesseract.jsfor OCR capabilitiespdf-parsefor PDF processingmammothfor DOCX supportxlsxfor Excel processingklassijs-astellenfor additional functionality- All other open-source contributors
- Creator: Larry Goddard
- Email: larryg@klassitech.co.uk
- LinkedIn: https://linkedin.com/in/larryg
- YouTube: https://youtube.com/@LarryG_01
For support, feature requests, or contributions, please visit our GitHub repository.
- Parameters:
- Parameters:
- Parameters:
Detects links in text using intelligent pattern matching.
Converts plain text with links to HTML with clickable links.
Processes multiple files simultaneously.
Saves extracted links to a JSON file for later use.
Loads previously saved links from JSON files.
Extracts structured data from documents based on their type.