/
index.js
182 lines (173 loc) 路 5.06 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/**
*
* Tesseract Worker adapter for browser
*
* @fileoverview Tesseract Worker adapter for browser
* @author Kevin Kwok <antimatter15@gmail.com>
* @author Guillermo Webster <gui@mit.edu>
* @author Jerome Wu <jeromewus@gmail.com>
*/
const check = require('check-types');
const resolveURL = require('resolve-url');
const axios = require('axios');
const b64toU8Array = require('./b64toU8Array');
const { defaultOptions } = require('../common/options');
const { version } = require('../../package.json');
/**
* readFromBlobOrFile
*
* @name readFromBlobOrFile
* @function
* @access private
* @param {object} blob A blob or file objec to read
* @param {function} res callback function after reading completes
*/
const readFromBlobOrFile = (blob, res) => {
const fileReader = new FileReader();
fileReader.onload = () => {
res(fileReader.result);
};
fileReader.readAsArrayBuffer(blob);
};
/**
* loadImage
*
* @name loadImage
* @function load image from different source
* @access private
* @param {string, object} image - image source, supported formats:
* string: URL string, can be relative path
* string: base64 image
* img HTMLElement: extract image source from src attribute
* video HTMLElement: extract image source from poster attribute
* canvas HTMLElement: extract image data by converting to Blob
* File instance: data from <input type="file" />
* @returns {array} binary image in array format
*/
const loadImage = (image) => {
if (check.string(image)) {
// Base64 Image
if (/data:image\/([a-zA-Z]*);base64,([^"]*)/.test(image)) {
return Promise.resolve(b64toU8Array(image.split(',')[1]));
}
// Image URL
return axios.get(resolveURL(image), {
responseType: 'arraybuffer',
})
.then(resp => resp.data);
}
if (check.instance(image, HTMLElement)) {
if (image.tagName === 'IMG') {
return loadImage(image.src);
}
if (image.tagName === 'VIDEO') {
return loadImage(image.poster);
}
if (image.tagName === 'CANVAS') {
return new Promise((res) => {
image.toBlob((blob) => {
readFromBlobOrFile(blob, res);
});
});
}
}
if (check.instance(image, File) || check.instance(image, Blob)) {
return new Promise((res) => {
readFromBlobOrFile(image, res);
});
}
return Promise.reject();
};
const downloadFile = (path, blob) => {
if (navigator.msSaveBlob) {
// IE 10+
navigator.msSaveBlob(blob, path);
} else {
const link = document.createElement('a');
// Browsers that support HTML5 download attribute
if (link.download !== undefined) {
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', path);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
};
/*
* Default options for browser worker
*/
exports.defaultOptions = {
...defaultOptions,
workerPath: (typeof process !== 'undefined' && process.env.TESS_ENV === 'development')
? resolveURL(`/dist/worker.dev.js?nocache=${Math.random().toString(36).slice(3)}`)
: `https://unpkg.com/tesseract.js@v${version}/dist/worker.min.js`,
/*
* If browser doesn't support WebAssembly,
* load ASM version instead
*/
corePath: `https://unpkg.com/tesseract.js-core@v2.0.0-beta.10/tesseract-core.${typeof WebAssembly === 'object' ? 'wasm' : 'asm'}.js`,
};
/**
* spawnWorker
*
* @name spawnWorker
* @function create a new Worker in browser
* @access public
* @param {object} instance - TesseractWorker instance
* @param {object} options
* @param {string} options.workerPath - worker script path
* @param {boolean} options.workerBlobURL - Use a blob:// URL for the worker script
*/
exports.spawnWorker = (instance, { workerPath, workerBlobURL }) => {
let worker;
if (Blob && URL && workerBlobURL) {
const blob = new Blob([`importScripts("${workerPath}");`], {
type: 'application/javascript',
});
worker = new Worker(URL.createObjectURL(blob));
} else {
worker = new Worker(workerPath);
}
worker.onmessage = ({ data }) => {
if (data.jobId.startsWith('Job')) {
instance.recv(data);
} else if (data.jobId.startsWith('Download')) {
const { path, data: d, type } = data;
const blob = new Blob([d], { type });
downloadFile(path, blob);
}
};
return worker;
};
/**
* terminateWorker
*
* @name terminateWorker
* @function terminate worker
* @access public
* @param {object} instance TesseractWorker instance
*/
exports.terminateWorker = (instance) => {
instance.worker.terminate();
};
/**
* sendPacket
*
* @name sendPacket
* @function send packet to worker and create a job
* @access public
* @param {object} instance TesseractWorker instance
* @param {object} iPacket data for worker
*/
exports.sendPacket = (instance, iPacket) => {
const packet = { ...iPacket };
loadImage(packet.payload.image)
.then(buf => new Uint8Array(buf))
.then((img) => {
packet.payload.image = Array.from(img);
instance.worker.postMessage(packet);
});
};