-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
72 lines (69 loc) · 2.33 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
const fs = require('fs');
const axios = require('axios');
const FormData = require('form-data');
/**
* Detect the input type between url, file path or base64 image
* @param {string} input Input string
* @return {string} input type
*/
function detectInput(input) {
if (input.startsWith('http')) return 'url';
if (input.startsWith('data:')) return 'base64Image';
return 'file';
}
/**
* Call OCR Space APIs
* @param {string} input Input file as url, file path or base64 image (required)
* @param {object} options Options
* @return {object} OCR results
*/
async function ocrSpace(input, options = {}) {
try {
if (!input || typeof input !== 'string') {
throw Error('Param input is required and must be typeof string');
}
const {
apiKey, ocrUrl, language, isOverlayRequired,
filetype, detectOrientation, isCreateSearchablePdf,
isSearchablePdfHideTextLayer, scale, isTable, OCREngine,
} = options;
const formData = new FormData();
const detectedInput = detectInput(input);
switch (detectedInput) {
case 'file':
formData.append('file', fs.createReadStream(input));
break;
case 'url':
case 'base64Image':
formData.append(detectedInput, input);
break;
}
formData.append('language', String(language || 'eng'));
formData.append('isOverlayRequired', String(isOverlayRequired || 'false'));
if (filetype) {
formData.append('filetype', String(filetype));
}
formData.append('detectOrientation', String(detectOrientation || 'false'));
formData.append('isCreateSearchablePdf', String(isCreateSearchablePdf || 'false'));
formData.append('isSearchablePdfHideTextLayer', String(isSearchablePdfHideTextLayer || 'false'));
formData.append('scale', String(scale || 'false'));
formData.append('isTable', String(isTable || 'false'));
formData.append('OCREngine', String(OCREngine || '1'));
const request = {
method: 'POST',
url: String(ocrUrl || 'https://api.ocr.space/parse/image'),
headers: {
apikey: String(apiKey || 'helloworld'),
...formData.getHeaders(),
},
data: formData,
maxContentLength: Infinity,
maxBodyLength: Infinity,
};
const { data } = await axios(request);
return data;
} catch (error) {
console.error(error);
}
}
exports.ocrSpace = ocrSpace;