-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpdfProcessing.py
More file actions
176 lines (132 loc) · 4.24 KB
/
pdfProcessing.py
File metadata and controls
176 lines (132 loc) · 4.24 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
try:
import collections.abc
except ImportError:
pass
from wand.image import Image as wi
import numpy as np
import cv2
import requests
import io
from matplotlib import pyplot as plt
import json
import re
# CHANGE REGION HERE
region = "westus"
URL = "https://"+region+".api.cognitive.microsoft.com/vision/v2.0/ocr"
HEADERS = {
'Content-Type': 'application/octet-stream',
# FILL SUBSCRIPTION KEY HERE
'Ocp-Apim-Subscription-Key': "YOUR_SUBSCRIPTION_KEY"
}
def getImageData(image):
buf = io.BytesIO()
plt.imsave(buf, image, format='png')
img_data = buf.getvalue()
return img_data
def getOCRFromImage(path):
img = cv2.imread(path, cv2.IMREAD_COLOR)
img_data = getImageData(img)
r = requests.post(URL,data=img_data,headers=HEADERS)
result = r.json()
return result
def getStructuredText(data):
structured_text = {}
structured_text['regions'] = []
regions = data["regions"]
for region in regions:
regionToAdd = {}
regionToAdd['lines'] = []
lines = region["lines"]
for l in lines:
line = ""
words = l["words"]
for w in words:
line += w["text"]
line += " "
regionToAdd['lines'].append(line)
structured_text['regions'].append(regionToAdd)
print(structured_text)
return structured_text
def getData(path):
f = open(path,"r")
json_data = f.read()
data = json.loads(json_data)
f.close()
return data
def saveToJSON(result,filename):
with open(filename, 'w') as outfile:
json.dump(result, outfile)
print("Done.")
def getDocumentStructure(numberOfPages,jsonFileName,pattern,titleDetection):
documentJSON = {}
documentJSON['pages'] = []
for i in range(1,numberOfPages+1):
page = {}
page['id'] = i
page['paragraphs'] = []
path = jsonFileName + str(i) + ".json"
data = getData(path)
regions = data['regions']
number = ""
title = ""
paragraph = {
'number': '',
'title': '',
'text': ''
}
detectTitle = False
textDetected = False
for r in regions:
for l in r['lines']:
if re.search(pattern,l):
paragraph['number'] = number
number = l
detectTitle = True
if detectTitle:
if(titleDetection):
paragraph['title'] = title
if(textDetected):
page['paragraphs'].append(paragraph)
title = l
if(not(titleDetection)):
title = ""
paragraph = {
'number': number,
'title': title,
'text': ""
}
detectTitle = False
if not(re.search(pattern,l)) and not(detectTitle and titleDetection):
paragraph['text'] += l
textDetected = True
page['paragraphs'].append(paragraph)
documentJSON['pages'].append(page)
return documentJSON
def convertToImages(path,outputName):
pdf = wi(filename=path,resolution=300)
pdfImage = pdf.convert("jpeg")
i=1
for img in pdfImage.sequence:
page = wi(image=img)
page.save(filename=outputName+str(i)+".jpg")
i+=1
print("Done.")
path = 'resources/sampleContract.pdf'
fileNames = "imgs-"
numberOfPages = 3
resultFile = "document.json"
# CHANGE HERE THE SEGMENTATION STYLE OF YOUR DOCUMENT
segmentationStyle = r"^\d\."
# IF YOUR DOCUMENT HAS TITLES AFTER SEGMENTATION, CHANGE THIS VALUE TO TRUE
titles = False
# CONVERT TO IMAGES
convertToImages(path,fileNames)
# PERFORM OCR
for i in range(1,numberOfPages+1):
imgpath = fileNames+str(i)+'.jpg'
data = getOCRFromImage(imgpath)
text = getStructuredText(data)
saveToJSON(text,fileNames+str(i)+'.json')
# GET DOCUMENT STRUCTURE
documentJSON = getDocumentStructure(numberOfPages,fileNames,segmentationStyle,titles)
saveToJSON(documentJSON,resultFile)