forked from whalebot-helmsman/ocrsdk.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathocrsdk.js
More file actions
273 lines (227 loc) · 6.92 KB
/
ocrsdk.js
File metadata and controls
273 lines (227 loc) · 6.92 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
if (typeof process == 'undefined' || process.argv[0] != "node") {
throw new Error("This code must be run on server side under NodeJS");
}
var http = require("http");
var https = require("https");
var url = require("url");
var sys = require("sys");
var events = require("events");
var fs = require('fs');
var xml2js = null;
try {
xml2js = require('xml2js');
} catch (err) {
throw new Error("xml2js module not found. Please install it with 'npm install xml2js'");
}
exports.create = function(applicationId, password) {
return new ocrsdk(applicationId, password);
}
exports.ProcessingSettings = ProcessingSettings;
/**
* TaskData object used in functions below has the following important fields:
* {string} id
* {string} status
* {string} resultUrl
*
* It is mapped from xml described at
* http://ocrsdk.com/documentation/specifications/status-codes/
*/
/**
* Create a new ocrsdk object.
*
* @constructor
* @param {string} applicationId Application Id.
* @param {string} password Password for the application you received in e-mail.
*/
function ocrsdk(applicationId, password) {
this.appId = applicationId;
this.password = password;
this.serverUrl = "http://cloud.ocrsdk.com"; // You can change it to
// https://cloud.ocrsdk.com if
// you need secure channel
}
/**
* Settings used to process image
*/
function ProcessingSettings() {
this.language = "English"; // Recognition language or comma-separated list
// of languages.
this.exportFormat = "txt"; // Output format. One of: txt, rtf, docx, xlsx,
// pptx, pdfSearchable, pdfTextAndImages, xml.
this.customOptions = ''; // Other custom options passed to RESTful call,
// like 'profile=documentArchiving'
}
/**
* Upload file to server and start processing.
*
* @param {string} filePath Path to the file to be processed.
* @param {ProcessingSettings} [settings] Image processing settings.
* @param {function(error, taskData)} callback The callback function.
*/
ocrsdk.prototype.processImage = function(filePath, settings, userCallback) {
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
userCallback(new Error("file " + filePath + " doesn't exist"), null);
return;
}
if (settings == null) {
settings = new ProcessingSettings();
}
var urlOptions = settings.asUrlParams();
var req = this._createTaskRequest('POST', '/processImage' + urlOptions,
userCallback);
var fileContents = fs.readFileSync(filePath);
req.write(fileContents);
req.end();
}
/**
* Get current task status.
*
* @param {string} taskId Task identifier as returned in taskData.id.
* @param {function(error, taskData)} callback The callback function.
*/
ocrsdk.prototype.getTaskStatus = function(taskId, userCallback) {
var req = this._createTaskRequest('GET', '/getTaskStatus?taskId=' + taskId,
userCallback);
req.end();
}
/**
* Wait until task processing is finished. You need to check task status after
* processing to see if you can download result.
*
* @param {string} taskId Task identifier as returned in taskData.id.
* @param {function(error, taskData)} callback The callback function.
*/
ocrsdk.prototype.waitForCompletion = function(taskId, userCallback) {
// Call getTaskStatus every second until task is completed
var recognizer = this;
function waitFunction() {
recognizer.getTaskStatus(taskId, function(error, taskData) {
if (error) {
userCallback(error, null);
return;
}
console.log("Task status is " + taskData.status);
if (taskData.status == 'Completed'
|| taskData.status == 'ProcessingFailed'
|| taskData.status == 'NotEnoughCredits') {
userCallback(null, taskData);
} else {
setTimeout(waitFunction, 1000);
}
});
}
waitFunction();
}
/**
* Download result of document processing. Task needs to be in 'Completed' state
* to call this function.
*
* @param {string} resultUrl URL where result is located
* @param {string} outputFilePath Path where to save downloaded file
* @param {function(error)} userCallback The callback function.
*/
ocrsdk.prototype.downloadResult = function(resultUrl, outputFilePath,
userCallback) {
var file = fs.createWriteStream(outputFilePath);
var parsed = url.parse(resultUrl);
var req = https.request(parsed, function(response) {
response.on('data', function(data) {
file.write(data);
});
response.on('end', function() {
file.end();
userCallback(null);
});
});
req.on('error', function(e) {
userCallback(error);
});
req.end();
}
/**
* Create http GET or POST request to cloud service with given path and
* parameters.
*
* @param {string} method 'GET' or 'POST'.
* @param {string} urlPath RESTful verb with parameters, e.g. '/processImage/language=French'.
* @param {function(error, TaskData)} User callback which is called when request is executed.
* @return {http.ClientRequest} Created request which is ready to be started.
*/
ocrsdk.prototype._createTaskRequest = function(method, urlPath,
taskDataCallback) {
/**
* Convert server xml response to TaskData. Calls taskDataCallback after.
*
* @param data Server XML response.
*/
function parseXmlResponse(data) {
var response = new Object();
var parser = new xml2js.Parser({
explicitCharKey : false,
trim : true,
explicitRoot : true,
mergeAttrs : true
});
parser.parseString(data, function(err, objResult) {
if (err) {
taskDataCallback(err, null);
return;
}
response = objResult;
});
if (response == null) {
return;
}
if (response.response == null || response.response.task == null
|| response.response.task[0] == null) {
if (response.error != null) {
taskDataCallback(new Error(response.error.message), null);
} else {
taskDataCallback(new Error("Unknown server resonse"), null);
}
return;
}
var task = response.response.task[0];
taskDataCallback(null, task);
}
function getServerResponse(res) {
res.setEncoding('utf8');
res.on('data', parseXmlResponse);
}
var requestOptions = url.parse(this.serverUrl + urlPath);
requestOptions.auth = this.appId + ":" + this.password;
requestOptions.method = method;
requestOptions.headers = {
'User-Agent' : "node.js client library"
};
var req = null;
if (requestOptions.protocol == 'http:') {
req = http.request(requestOptions, getServerResponse);
} else {
req = https.request(requestOptions, getServerResponse);
}
req.on('error', function(e) {
taskDataCallback(e, null);
});
return req;
}
/**
* Convert processing settings to string passed to RESTful request.
*/
ProcessingSettings.prototype.asUrlParams = function() {
var result = '';
if (this.language.length != null) {
result = '?language=' + this.language;
} else {
result = '?language=English';
}
if (this.exportFormat.length != null) {
result += '&exportFormat=' + this.exportFormat;
} else {
result += "&exportFormat=txt"
}
if (this.customOptions.length != 0) {
result += '?' + this.customOptions;
}
return result;
}