/
layout.go
236 lines (189 loc) Β· 6.76 KB
/
layout.go
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
package textractor
import (
"fmt"
"math"
"sort"
"strings"
"github.com/aws/aws-sdk-go-v2/service/textract/types"
)
type LayoutChild interface {
ID() string
Text(optFns ...func(*TextLinearizationOptions)) string
BoundingBox() *BoundingBox
}
type Layout struct {
base
children []LayoutChild
noNewLines bool
}
func (l *Layout) AddChildren(children ...LayoutChild) {
l.children = append(l.children, children...)
}
func (l *Layout) Text(optFns ...func(*TextLinearizationOptions)) string {
opts := DefaultLinerizationOptions
for _, fn := range optFns {
fn(&opts)
}
if (l.BlockType() == types.BlockTypeLayoutHeader && opts.HideHeaderLayout) ||
(l.BlockType() == types.BlockTypeLayoutFooter && opts.HideFooterLayout) ||
(l.BlockType() == types.BlockTypeLayoutFigure && opts.HideFigureLayout) ||
(l.BlockType() == types.BlockTypeLayoutPageNumber && opts.HidePageNumberLayout) {
return ""
}
var text string
switch l.BlockType() { // nolint exhaustive
case types.BlockTypeLayoutList:
items := make([]string, 0, len(l.children))
for _, c := range l.children {
itemText := c.Text(func(tlo *TextLinearizationOptions) {
*tlo = opts
})
if opts.RemoveNewLinesInListElements {
itemText = strings.ReplaceAll(itemText, "\n", " ")
}
items = append(items, fmt.Sprintf("%s%s%s", opts.ListElementPrefix, itemText, opts.ListElementSuffix))
}
text = strings.Join(items, opts.ListElementSeparator)
case types.BlockTypeLayoutPageNumber:
text = l.linearizeChildren(l.children, opts)
text = fmt.Sprintf("%s%s%s", opts.PageNumberPrefix, text, opts.PageNumberSuffix)
text = opts.OnLinerizedPageNumber(text)
case types.BlockTypeLayoutTitle:
text = l.linearizeChildren(l.children, opts)
text = fmt.Sprintf("%s%s%s", opts.TitlePrefix, text, opts.TitleSuffix)
text = opts.OnLinerizedTitle(text)
case types.BlockTypeLayoutSectionHeader:
text = l.linearizeChildren(l.children, opts)
text = fmt.Sprintf("%s%s%s", opts.SectionHeaderPrefix, text, opts.SectionHeaderSuffix)
text = opts.OnLinerizedSectionHeader(text)
default:
text = l.linearizeChildren(l.children, opts)
}
invalidSeparator := strings.Repeat("\n", opts.MaxNumberOfConsecutiveNewLines+1)
validSeperator := strings.Repeat("\n", opts.MaxNumberOfConsecutiveNewLines)
for strings.Contains(text, invalidSeparator) {
text = strings.ReplaceAll(text, invalidSeparator, validSeperator)
}
return text
}
func (l *Layout) linearizeChildren(children []LayoutChild, opts TextLinearizationOptions) string {
var (
text string
prev LayoutChild
)
for _, group := range groupElementsHorizontally(children, opts.HeuristicOverlapRatio) {
sort.Slice(group, func(i, j int) bool {
return group[i].BoundingBox().Left() < group[j].BoundingBox().Left()
})
addRowSeparatorIfTableLayout := true
for i, child := range group {
childText := child.Text(func(tlo *TextLinearizationOptions) {
*tlo = opts
})
switch child.(type) {
case *Table:
text += fmt.Sprintf("%s%s%s", opts.TableLayoutPrefix, childText, opts.TableLayoutSuffix)
addRowSeparatorIfTableLayout = false
case *KeyValue:
text += fmt.Sprintf("%s%s%s", opts.KeyValueLayoutPrefix, childText, opts.KeyValueLayoutSuffix)
addRowSeparatorIfTableLayout = false
default:
if l.BlockType() == types.BlockTypeLayoutTable {
sep := opts.TableColumnSeparator
if i == 0 {
sep = ""
}
text += sep + childText
} else if partOfSameParagraph(prev, child, opts) {
text += opts.SameParagraphSeparator + childText
} else {
sep := ""
if prev != nil {
sep = opts.LayoutElementSeparator
}
text += sep + childText
}
prev = child
}
}
if l.BlockType() == types.BlockTypeLayoutTable && addRowSeparatorIfTableLayout {
text = text + opts.TableRowSeparator
}
prev = &Line{
base: base{
boundingBox: NewEnclosingBoundingBox(group...),
},
}
}
if l.noNewLines {
// Replace all occurrences of \n with a space
text = strings.ReplaceAll(text, "\n", " ")
// Replace consecutive spaces with a single space
for strings.Contains(text, " ") {
text = strings.ReplaceAll(text, " ", " ")
}
}
return text
}
// groupElementsHorizontally groups elements horizontally based on their vertical positions.
// It takes a slice of elements and an overlap ratio as parameters, and returns a 2D slice of grouped elements.
func groupElementsHorizontally(elements []LayoutChild, overlapRatio float64) [][]LayoutChild {
// Create a copy of the elements to avoid modifying the original slice
sortedElements := make([]LayoutChild, len(elements))
copy(sortedElements, elements)
// Sort elements based on the top position of their bounding boxes
sort.Slice(sortedElements, func(i, j int) bool {
return sortedElements[i].BoundingBox().Top() < sortedElements[j].BoundingBox().Top()
})
var groupedElements [][]LayoutChild
// Check if the sorted elements slice is empty
if len(sortedElements) == 0 {
return groupedElements
}
// verticalOverlap calculates the vertical overlap between two children
verticalOverlap := func(child1, child2 LayoutChild) float64 {
t1 := child1.BoundingBox().Top()
h1 := child1.BoundingBox().Height()
t2 := child2.BoundingBox().Top()
h2 := child2.BoundingBox().Height()
top := math.Max(t1, t2)
bottom := math.Min(t1+h1, t2+h2)
return math.Max(bottom-top, 0)
}
// shouldGroup determines whether a line should be grouped with an existing group of lines
shouldGroup := func(child LayoutChild, group []LayoutChild) bool {
if len(group) == 0 {
return false
}
maxHeight := 0.0
for _, l := range group {
maxHeight = math.Max(maxHeight, l.BoundingBox().Height())
}
totalOverlap := 0.0
for _, l := range group {
totalOverlap += verticalOverlap(child, l)
}
return totalOverlap/maxHeight >= overlapRatio
}
// Initialize the first group with the first element
currentGroup := []LayoutChild{sortedElements[0]}
// Iterate through the sorted elements and group them horizontally
for _, element := range sortedElements[1:] {
if shouldGroup(element, currentGroup) {
currentGroup = append(currentGroup, element)
} else {
groupedElements = append(groupedElements, currentGroup)
currentGroup = []LayoutChild{element}
}
}
// Add the last group to the result
groupedElements = append(groupedElements, currentGroup)
return groupedElements
}
func partOfSameParagraph(child1, child2 LayoutChild, options TextLinearizationOptions) bool {
if child1 != nil && child2 != nil {
return math.Abs(child1.BoundingBox().Left()-child2.BoundingBox().Left()) <= options.HeuristicHTolerance*child1.BoundingBox().Width() &&
math.Abs(child1.BoundingBox().Top()+child1.BoundingBox().Height()-child2.BoundingBox().Top()) <= options.HeuristicOverlapRatio*math.Min(child1.BoundingBox().Height(), child2.BoundingBox().Height())
}
return false
}