-
Notifications
You must be signed in to change notification settings - Fork 1
/
OCRinterpretation.py
90 lines (66 loc) · 2.29 KB
/
OCRinterpretation.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
import json
import re
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
numberOfPages = 3
jsonFileName = "imgs-"
filename = "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
documentJSON = getDocumentStructure(numberOfPages,jsonFileName,segmentationStyle,titles)
saveToJSON(documentJSON,filename)