forked from aws-samples/amazon-textract-textractor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tdp.py
241 lines (200 loc) · 8.49 KB
/
tdp.py
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
import os
import time
from helper import AwsHelper, FileHelper
class Input:
def __init__(self):
self.bucketName = ""
self.documentPath = ""
self.awsRegion = "us-east-1"
self.detectText = False
self.detectForms = False
self.detectTables = False
self.isLocalDocument = False
self.documentType = ""
def __str__(self):
s = "---------------------------------------------\n"
if(not self.isLocalDocument):
s = s + "Bucket Name: {}\n".format(self.bucketName)
s = s + "Document: {}\n".format(self.documentPath)
s = s + "Text: {}\n".format(self.detectText)
s = s + "Form: {}\n".format(self.detectForms)
s = s + "Table: {}\n".format(self.detectTables)
s = s + "AWS Region: {}".format(self.awsRegion)
s = s + "---------------------------------------------\n"
class ImageProcessor:
def __init__(self, inputParameters):
''' Constructor. '''
self.inputParameters = inputParameters
def _callTextract(self):
textract = AwsHelper().getClient('textract', self.inputParameters.awsRegion)
if(not self.inputParameters.detectForms and not self.inputParameters.detectTables):
if(self.inputParameters.isLocalDocument):
with open(self.inputParameters.documentPath, 'rb') as document:
imageData = document.read()
imageBytes = bytearray(imageData)
response = textract.detect_document_text(Document={'Bytes': imageBytes})
else:
response = textract.detect_document_text(
Document={
'S3Object': {
'Bucket': self.inputParameters.bucketName,
'Name': self.inputParameters.documentPath
}
}
)
else:
features = []
if(self.inputParameters.detectTables):
features.append("TABLES")
if(self.inputParameters.detectForms):
features.append("FORMS")
if(self.inputParameters.isLocalDocument):
with open(self.inputParameters.documentPath, 'rb') as document:
imageData = document.read()
imageBytes = bytearray(imageData)
response = textract.analyze_document(Document={'Bytes': imageBytes} , FeatureTypes=features)
else:
response = textract.analyze_document(
Document={
'S3Object': {
'Bucket': self.inputParameters.bucketName,
'Name': self.inputParameters.documentPath
}
},
FeatureTypes=features
)
return response
def run(self):
response = self._callTextract()
return response
class PdfProcessor:
def __init__(self, inputParameters):
self.inputParameters = inputParameters
def _startJob(self):
response = None
client = AwsHelper().getClient('textract', self.inputParameters.awsRegion)
if(not self.inputParameters.detectForms and not self.inputParameters.detectTables):
response = client.start_document_text_detection(
DocumentLocation={
'S3Object': {
'Bucket': self.inputParameters.bucketName,
'Name': self.inputParameters.documentPath
}
})
else:
features = []
if(self.inputParameters.detectTables):
features.append("TABLES")
if(self.inputParameters.detectForms):
features.append("FORMS")
response = client.start_document_analysis(
DocumentLocation={
'S3Object': {
'Bucket': self.inputParameters.bucketName,
'Name': self.inputParameters.documentPath
}
},
FeatureTypes=features
)
return response["JobId"]
def _isJobComplete(self, jobId):
time.sleep(5)
client = AwsHelper().getClient('textract', self.inputParameters.awsRegion)
if(not self.inputParameters.detectForms and not self.inputParameters.detectTables):
response = client.get_document_text_detection(JobId=jobId)
else:
response = client.get_document_analysis(JobId=jobId)
status = response["JobStatus"]
print(status)
while(status == "IN_PROGRESS"):
time.sleep(5)
if(not self.inputParameters.detectForms and not self.inputParameters.detectTables):
response = client.get_document_text_detection(JobId=jobId)
else:
response = client.get_document_analysis(JobId=jobId)
status = response["JobStatus"]
print(status)
return status
def _getJobResults(self, jobId):
pages = []
time.sleep(5)
client = AwsHelper().getClient('textract', self.inputParameters.awsRegion)
if(not self.inputParameters.detectForms and not self.inputParameters.detectTables):
response = client.get_document_text_detection(JobId=jobId)
else:
response = client.get_document_analysis(JobId=jobId)
pages.append(response)
print("Resultset page recieved: {}".format(len(pages)))
nextToken = None
if('NextToken' in response):
nextToken = response['NextToken']
#print("Next token: {}".format(nextToken))
while(nextToken):
time.sleep(5)
if(not self.inputParameters.detectForms and not self.inputParameters.detectTables):
response = client.get_document_text_detection(JobId=jobId, NextToken=nextToken)
else:
response = client.get_document_analysis(JobId=jobId, NextToken=nextToken)
pages.append(response)
print("Resultset page recieved: {}".format(len(pages)))
nextToken = None
if('NextToken' in response):
nextToken = response['NextToken']
#print("Next token: {}".format(nextToken))
#if(len(pages) > 20):
# break
return pages
def run(self):
jobId = self._startJob()
print("Started Asyc Job with Id: {}".format(jobId))
status = self._isJobComplete(jobId)
if(status == "SUCCEEDED"):
responsePages = self._getJobResults(jobId)
return responsePages
class DocumentProcessor:
def __init__(self, bucketName, documentPath, awsRegion, detectText, detectForms, detectTables):
ip = Input()
if(bucketName):
ip.bucketName = bucketName
if(documentPath):
ip.documentPath = documentPath
if(awsRegion):
ip.awsRegion = awsRegion
if(detectText):
ip.detectText = detectText
if(detectForms):
ip.detectForms = detectForms
if(detectTables):
ip.detectTables = detectTables
if(not ip.bucketName and not ip.documentPath):
raise Exception("Document is required.")
if(ip.bucketName):
ip.isLocalDocument = False
else:
ip.isLocalDocument = True
ext = FileHelper.getFileExtenstion(ip.documentPath).lower()
if(ext == "pdf"):
ip.documentType = "PDF"
elif(ext == "jpg" or ext == "jpeg" or ext == "png"):
ip.documentType = "IMAGE"
else:
raise Exception("Document should be jpg/jpeg, png or pdf.")
if(ip.documentType == "PDF" and ip.isLocalDocument):
raise Exception("PDF must be in S3 bucket.")
if(ip.detectText == False and ip.detectForms == False and ip.detectTables == False):
raise Exception("Select at least one option to extract text, form or table")
self.inputParameters = ip
def run(self):
print("Calling Textract...")
# Call and Get results from Textract
if(self.inputParameters.documentType == "IMAGE"):
ip = ImageProcessor(self.inputParameters)
response = ip.run()
responsePages = []
responsePages.append(response)
self.responsePages = responsePages
else:
pp = PdfProcessor(self.inputParameters)
responsePages = pp.run()
self.responsePages = responsePages
return self.responsePages