-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
208 lines (193 loc) · 5.56 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
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
const fs = require('fs');
const path = require('path');
// Rimraf to clean up temp dir
const rimraf = require('rimraf');
// Load tesseract.js for OCR
const Tesseract = require('tesseract.js');
// Load the AWS SDK for Node.js
const AWS = require('aws-sdk');
// Set the region
AWS.config.update({ region: process.env.AWS_REGION || 'eu-west-1' });
// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: '2012-11-05' });
// Create an S3 object
var s3 = new AWS.S3();
// URL to SQS Queue - Environment Variable
var queueURL = process.env.AWS_SQS_QUEUE_URL;
// ARN to OCR Input Bucket
var S3input = process.env.AWS_S3_OCR_INPUT;
// ARN to OCR Output Bucket
var S3output = process.env.AWS_S3_OCR_OUTPUT;
// Temp Dir
var tmpDir = process.env.OCR_TEMP_DIR || './tmp';
var params = {
AttributeNames: [
"SentTimestamp"
],
MaxNumberOfMessages: 1,
MessageAttributeNames: [
"All"
],
QueueUrl: queueURL,
VisibilityTimeout: process.env.AWS_SQS_VISIBILITY_TIMEOUT || 300, // Setting a very high value here as OCR takes time
WaitTimeSeconds: process.env.AWS_SQS_WAIT_TIME_SECONDS || 10
};
// Receive messages from queue
const receiveAndProcess = () => {
try {
sqs.receiveMessage(params, function (err, data) {
if (err) {
console.log("Receive Error", err);
} else if (data.Messages) {
console.log("Message received. Processing...");
processMessage(data.Messages[0], (err) => {
if (err) {
console.log("Error processing message", err)
deleteMessage(data.Messages[0], (err, data) => {
if (err) {
console.log("Delete Error", err);
} else {
console.log("Message Deleted", data);
}
});
} else {
deleteMessage(data.Messages[0], (err, data) => {
if (err) {
console.log("Delete Error", err);
} else {
console.log("Message Deleted", data);
receiveAndProcess();
}
});
}
});
} else {
console.log(new Date(), "No new messages to process...");
receiveAndProcess();
}
});
} catch (e) {
console.log("An error occured receiving message from SQS: " + e)
}
}
// Process a received message
/* Example Message:
{
"Records": [
{
"eventVersion": "2.1",
"eventSource": "aws:s3",
"awsRegion": "eu-west-1",
"eventTime": "2020-11-16T19:10:20.178Z",
"eventName": "ObjectCreated:Put",
"userIdentity": {
"principalId": "example"
},
"requestParameters": {
"sourceIPAddress": "10.20.30.40"
},
"responseElements": {
"x-amz-request-id": "...",
"x-amz-id-2": "..."
},
"s3": {
"s3SchemaVersion": "1.0",
"configurationId": "09c216f5-caa0-4b93-9853-a86dbbf9a8b5",
"bucket": {
"name": "inputbucket",
"ownerIdentity": {
"principalId": "..."
},
"arn": "arn:aws:s3:::inputbucket"
},
"object": {
"key": "demo.png",
"size": 70668,
"eTag": "f5e86c36a7874ba2492b0143ec56360d",
"sequencer": "005FB2CE9EA7BE0F74"
}
}
}
]
}
*/
const processMessage = (message, callback) => {
try {
var payload = JSON.parse(message.Body).Records[0];
} catch (e) {
callback("Invalid JSON format for message body. " + e)
}
if (payload&&payload.eventName&&payload.eventName=="ObjectCreated:Put") {
downloadFileToTemp(payload.s3.object.key, () => {
console.log("Downloaded", payload.s3.object.key, "to", tmpDir);
doOCR(payload.s3.object.key, () => {
uploadFileToResultBucket(payload.s3.object.key + '.txt', () => {
cleanUpTemp(()=>{
callback(null);
})
});
});
})
} else {
callback("Message does not contain an OCR Input File");
}
}
// Delete message from queue once OCR is completed
const deleteMessage = (message, callback) => {
var deleteParams = {
QueueUrl: queueURL,
ReceiptHandle: message.ReceiptHandle
};
sqs.deleteMessage(deleteParams, callback);
}
// Download file referenced in message from input bucket
const downloadFileToTemp = (key, callback) => {
var s3Params = {
Bucket: S3input,
Key: key
};
let readStream = s3.getObject(s3Params).createReadStream();
let writeStream = fs.createWriteStream(path.join(tmpDir, key));
readStream.pipe(writeStream);
readStream.on('finish', () => {
callback();
});
}
// Upload OCR text to output bucket
const uploadFileToResultBucket = (file, callback) => {
var s3Params = {
Bucket: S3output,
Key: file,
Body: fs.createReadStream(path.join(tmpDir, file))
};
// call S3 to retrieve upload file to specified bucket
s3.upload(s3Params, function (err, data) {
if (err) {
console.log("Error uploading result file", err);
callback();
} if (data) {
console.log("Upload Success", data.Location);
callback();
}
});
}
// Cleanup temp dir
const cleanUpTemp = (callback) => {
console.log("Cleaning up temp directory")
rimraf(path.join(tmpDir,"*"), callback);
}
// OCR Function calling Tesseract.js
const doOCR = (file, callback) => {
console.log("Starting OCR work... this might take some time");
Tesseract.recognize(
path.join(tmpDir, file),
'eng',
{ logger: m => { } }
).then(({ data: { text } }) => {
console.log("Done. Writing results to file.")
fs.writeFile(path.join(tmpDir, file + ".txt"), text, () => {
callback();
});
});
}
receiveAndProcess();