-
Notifications
You must be signed in to change notification settings - Fork 4
/
trp.py
653 lines (523 loc) · 16.5 KB
/
trp.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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
import json
class BoundingBox:
def __init__(self, width, height, left, top):
self._width = width
self._height = height
self._left = left
self._top = top
def __str__(self):
return "width: {}, height: {}, left: {}, top: {}".format(self._width, self._height, self._left, self._top)
@property
def width(self):
return self._width
@property
def height(self):
return self._height
@property
def left(self):
return self._left
@property
def top(self):
return self._top
class Polygon:
def __init__(self, x, y):
self._x = x
self._y = y
def __str__(self):
return "x: {}, y: {}".format(self._x, self._y)
@property
def x(self):
return self._x
@property
def y(self):
return self._y
class Geometry:
def __init__(self, geometry):
boundingBox = geometry["BoundingBox"]
polygon = geometry["Polygon"]
bb = BoundingBox(boundingBox["Width"], boundingBox["Height"], boundingBox["Left"], boundingBox["Top"])
pgs = []
for pg in polygon:
pgs.append(Polygon(pg["X"], pg["Y"]))
self._boundingBox = bb
self._polygon = pgs
def __str__(self):
s = "BoundingBox: {}\n".format(str(self._boundingBox))
return s
@property
def boundingBox(self):
return self._boundingBox
@property
def polygon(self):
return self._polygon
class Word:
def __init__(self, block, blockMap):
self._block = block
self._confidence = block['Confidence']
self._geometry = Geometry(block['Geometry'])
self._id = block['Id']
self._text = ""
if(block['Text']):
self._text = block['Text']
def __str__(self):
return self._text
@property
def confidence(self):
return self._confidence
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def text(self):
return self._text
@property
def block(self):
return self._block
class Line:
def __init__(self, block, blockMap):
self._block = block
self._confidence = block['Confidence']
self._geometry = Geometry(block['Geometry'])
self._id = block['Id']
self._text = ""
if(block['Text']):
self._text = block['Text']
self._words = []
if('Relationships' in block and block['Relationships']):
for rs in block['Relationships']:
if(rs['Type'] == 'CHILD'):
for cid in rs['Ids']:
if(blockMap[cid]["BlockType"] == "WORD"):
self._words.append(Word(blockMap[cid], blockMap))
def __str__(self):
s = "Line\n==========\n"
s = s + self._text + "\n"
s = s + "Words\n----------\n"
for word in self._words:
s = s + "[{}]".format(str(word))
return s
@property
def confidence(self):
return self._confidence
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def words(self):
return self._words
@property
def text(self):
return self._text
@property
def block(self):
return self._block
class SelectionElement:
def __init__(self, block, blockMap):
self._confidence = block['Confidence']
self._geometry = Geometry(block['Geometry'])
self._id = block['Id']
self._selectionStatus = block['SelectionStatus']
@property
def confidence(self):
return self._confidence
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def selectionStatus(self):
return self._selectionStatus
class FieldKey:
def __init__(self, block, children, blockMap):
self._block = block
self._confidence = block['Confidence']
self._geometry = Geometry(block['Geometry'])
self._id = block['Id']
self._text = ""
self._content = []
t = []
for eid in children:
wb = blockMap[eid]
if(wb['BlockType'] == "WORD"):
w = Word(wb, blockMap)
self._content.append(w)
t.append(w.text)
if(t):
self._text = ' '.join(t)
def __str__(self):
return self._text
@property
def confidence(self):
return self._confidence
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def content(self):
return self._content
@property
def text(self):
return self._text
@property
def block(self):
return self._block
class FieldValue:
def __init__(self, block, children, blockMap):
self._block = block
self._confidence = block['Confidence']
self._geometry = Geometry(block['Geometry'])
self._id = block['Id']
self._text = ""
self._content = []
t = []
for eid in children:
wb = blockMap[eid]
if(wb['BlockType'] == "WORD"):
w = Word(wb, blockMap)
self._content.append(w)
t.append(w.text)
elif(wb['BlockType'] == "SELECTION_ELEMENT"):
se = SelectionElement(wb, blockMap)
self._content.append(se)
self._text = se.selectionStatus
if(t):
self._text = ' '.join(t)
def __str__(self):
return self._text
@property
def confidence(self):
return self._confidence
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def content(self):
return self._content
@property
def text(self):
return self._text
@property
def block(self):
return self._block
class Field:
def __init__(self, block, blockMap):
self._key = None
self._value = None
for item in block['Relationships']:
if(item["Type"] == "CHILD"):
self._key = FieldKey(block, item['Ids'], blockMap)
elif(item["Type"] == "VALUE"):
for eid in item['Ids']:
vkvs = blockMap[eid]
if 'VALUE' in vkvs['EntityTypes']:
if('Relationships' in vkvs):
for vitem in vkvs['Relationships']:
if(vitem["Type"] == "CHILD"):
self._value = FieldValue(vkvs, vitem['Ids'], blockMap)
def __str__(self):
s = "\nField\n==========\n"
k = ""
v = ""
if(self._key):
k = str(self._key)
if(self._value):
v = str(self._value)
s = s + "Key: {}\nValue: {}".format(k, v)
return s
@property
def key(self):
return self._key
@property
def value(self):
return self._value
class Form:
def __init__(self):
self._fields = []
self._fieldsMap = {}
def addField(self, field):
self._fields.append(field)
self._fieldsMap[field.key.text] = field
def __str__(self):
s = ""
for field in self._fields:
s = s + str(field) + "\n"
return s
@property
def fields(self):
return self._fields
def getFieldByKey(self, key):
field = None
if(key in self._fieldsMap):
field = self._fieldsMap[key]
return field
def searchFieldsByKey(self, key):
searchKey = key.lower()
results = []
for field in self._fields:
if(field.key and searchKey in field.key.text.lower()):
results.append(field)
return results
class Cell:
def __init__(self, block, blockMap):
self._block = block
self._confidence = block['Confidence']
self._rowIndex = block['RowIndex']
self._columnIndex = block['ColumnIndex']
self._rowSpan = block['RowSpan']
self._columnSpan = block['ColumnSpan']
self._geometry = Geometry(block['Geometry'])
self._id = block['Id']
self._content = []
self._text = ""
if('Relationships' in block and block['Relationships']):
for rs in block['Relationships']:
if(rs['Type'] == 'CHILD'):
for cid in rs['Ids']:
blockType = blockMap[cid]["BlockType"]
if(blockType == "WORD"):
w = Word(blockMap[cid], blockMap)
self._content.append(w)
self._text = self._text + w.text + ' '
elif(blockType == "SELECTION_ELEMENT"):
se = SelectionElement(blockMap[cid], blockMap)
self._content.append(se)
self._text = self._text + se.selectionStatus + ', '
def __str__(self):
return self._text
@property
def confidence(self):
return self._confidence
@property
def rowIndex(self):
return self._rowIndex
@property
def columnIndex(self):
return self._columnIndex
@property
def rowSpan(self):
return self._rowSpan
@property
def columnSpan(self):
return self._columnSpan
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def content(self):
return self._content
@property
def text(self):
return self._text
@property
def block(self):
return self._block
class Row:
def __init__(self):
self._cells = []
def __str__(self):
s = ""
for cell in self._cells:
s = s + "[{}]".format(str(cell))
return s
@property
def cells(self):
return self._cells
class Table:
def __init__(self, block, blockMap):
self._block = block
self._confidence = block['Confidence']
self._geometry = Geometry(block['Geometry'])
self._id = block['Id']
self._rows = []
ri = 1
row = Row()
cell = None
if('Relationships' in block and block['Relationships']):
for rs in block['Relationships']:
if(rs['Type'] == 'CHILD'):
for cid in rs['Ids']:
cell = Cell(blockMap[cid], blockMap)
if(cell.rowIndex > ri):
self._rows.append(row)
row = Row()
ri = cell.rowIndex
row.cells.append(cell)
if(row and row.cells):
self._rows.append(row)
def __str__(self):
s = "Table\n==========\n"
for row in self._rows:
s = s + "Row\n==========\n"
s = s + str(row) + "\n"
return s
@property
def confidence(self):
return self._confidence
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def rows(self):
return self._rows
@property
def block(self):
return self._block
class Page:
def __init__(self, blocks, blockMap):
self._blocks = blocks
self._text = ""
self._lines = []
self._form = Form()
self._tables = []
self._content = []
self._parse(blockMap)
def __str__(self):
s = "Page\n==========\n"
for item in self._content:
s = s + str(item) + "\n"
return s
def _parse(self, blockMap):
for item in self._blocks:
if item["BlockType"] == "PAGE":
self._geometry = Geometry(item['Geometry'])
self._id = item['Id']
elif item["BlockType"] == "LINE":
l = Line(item, blockMap)
self._lines.append(l)
self._content.append(l)
self._text = self._text + l.text + '\n'
elif item["BlockType"] == "TABLE":
t = Table(item, blockMap)
self._tables.append(t)
self._content.append(t)
elif item["BlockType"] == "KEY_VALUE_SET":
if 'KEY' in item['EntityTypes']:
f = Field(item, blockMap)
if(f.key):
self._form.addField(f)
self._content.append(f)
else:
print("WARNING: Detected K/V where key does not have content. Excluding key from output.")
print(f)
print(item)
def getLinesInReadingOrder(self):
columns = []
lines = []
for item in self._lines:
column_found=False
for index, column in enumerate(columns):
bbox_left = item.geometry.boundingBox.left
bbox_right = item.geometry.boundingBox.left + item.geometry.boundingBox.width
bbox_centre = item.geometry.boundingBox.left + item.geometry.boundingBox.width/2
column_centre = column['left'] + column['right']/2
if (bbox_centre > column['left'] and bbox_centre < column['right']) or (column_centre > bbox_left and column_centre < bbox_right):
#Bbox appears inside the column
lines.append([index, item.text])
column_found=True
break
if not column_found:
columns.append({'left':item.geometry.boundingBox.left, 'right':item.geometry.boundingBox.left + item.geometry.boundingBox.width})
lines.append([len(columns)-1, item.text])
lines.sort(key=lambda x: x[0])
return lines
def getTextInReadingOrder(self):
lines = self.getLinesInReadingOrder()
text = ""
for line in lines:
text = text + line[1] + '\n'
return text
@property
def blocks(self):
return self._blocks
@property
def text(self):
return self._text
@property
def lines(self):
return self._lines
@property
def form(self):
return self._form
@property
def tables(self):
return self._tables
@property
def content(self):
return self._content
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
class Document:
def __init__(self, responsePages):
if(not isinstance(responsePages, list)):
rps = []
rps.append(responsePages)
responsePages = rps
self._responsePages = responsePages
self._pages = []
self._parse()
def __str__(self):
s = "\nDocument\n==========\n"
for p in self._pages:
s = s + str(p) + "\n\n"
return s
def _parseDocumentPagesAndBlockMap(self):
blockMap = {}
documentPages = []
documentPage = None
for page in self._responsePages:
for block in page['Blocks']:
if('BlockType' in block and 'Id' in block):
blockMap[block['Id']] = block
if(block['BlockType'] == 'PAGE'):
if(documentPage):
documentPages.append({"Blocks" : documentPage})
documentPage = []
documentPage.append(block)
else:
documentPage.append(block)
if(documentPage):
documentPages.append({"Blocks" : documentPage})
return documentPages, blockMap
def _parse(self):
self._responseDocumentPages, self._blockMap = self._parseDocumentPagesAndBlockMap()
for documentPage in self._responseDocumentPages:
page = Page(documentPage["Blocks"], self._blockMap)
self._pages.append(page)
@property
def blocks(self):
return self._responsePages
@property
def pageBlocks(self):
return self._responseDocumentPages
@property
def pages(self):
return self._pages
def getBlockById(self, blockId):
block = None
if(self._blockMap and blockId in self._blockMap):
block = self._blockMap[blockId]
return block