-
Notifications
You must be signed in to change notification settings - Fork 1
/
splitter.go
136 lines (100 loc) · 2.45 KB
/
splitter.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
package text
import (
"strings"
"unicode/utf8"
)
type Splitter struct {
ChunkSize int
ChunkOverlap int
Separators []string
LenFunc func(string) int
}
func NewSplitter() Splitter {
s := Splitter{
ChunkSize: 1500,
ChunkOverlap: 0,
Separators: []string{
"\n\n",
"\n",
" ",
"",
},
LenFunc: utf8.RuneCountInString,
}
return s
}
func (s *Splitter) Split(text string) []string {
separator := s.textSeparator(text)
result := make([]string, 0)
chunks := make([]string, 0)
for _, split := range strings.Split(text, separator) {
if s.LenFunc(split) < s.ChunkSize {
chunks = append(chunks, split)
continue
}
if len(chunks) > 0 {
result = append(result, s.mergeSplits(chunks, separator)...)
clear(chunks)
}
result = append(result, s.Split(split)...)
}
if len(chunks) > 0 {
result = append(result, s.mergeSplits(chunks, separator)...)
}
return result
}
func (s *Splitter) mergeSplits(splits []string, separator string) []string {
total := 0
result := make([]string, 0)
current := make([]string, 0)
for _, split := range splits {
splitlength := total + s.LenFunc(split)
if len(current) != 0 {
splitlength += s.LenFunc(separator)
}
if splitlength > s.ChunkSize && len(current) > 0 {
doc := joinDocs(current, separator)
if doc != "" {
result = append(result, doc)
}
for shouldPop(s.ChunkOverlap, s.ChunkSize, total, s.LenFunc(split), s.LenFunc(separator), len(current)) {
total -= s.LenFunc(current[0])
if len(current) > 1 {
total -= s.LenFunc(separator)
}
current = current[1:]
}
}
current = append(current, split)
total += s.LenFunc(split)
if len(current) > 1 {
total += s.LenFunc(separator)
}
}
doc := joinDocs(current, separator)
if doc != "" {
result = append(result, doc)
}
return result
}
func joinDocs(docs []string, separator string) string {
return strings.TrimSpace(strings.Join(docs, separator))
}
func shouldPop(chunkOverlap, chunkSize, total, splitLen, separatorLen, currentDocLen int) bool {
docsNeededToAddSep := 2
if currentDocLen < docsNeededToAddSep {
separatorLen = 0
}
return currentDocLen > 0 && (total > chunkOverlap || (total+splitLen+separatorLen > chunkSize && total > 0))
}
func (s *Splitter) textSeparator(text string) string {
for _, sep := range s.Separators {
if strings.Contains(text, sep) {
return sep
}
}
if len(s.Separators) > 0 {
return s.Separators[len(s.Separators)-1]
}
return ""
}