-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchunk.go
More file actions
66 lines (55 loc) · 1.36 KB
/
chunk.go
File metadata and controls
66 lines (55 loc) · 1.36 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
package magictext
import (
"fmt"
"strings"
)
type Chunk struct {
ID string `json:"id"`
Height int `json:"height"`
Seq int `json:"seq"`
Text string `json:"text"`
Tokens int `json:"tokens"`
Children ChunkSlice `json:"children"`
}
func NewChunk(seq int, text string) *Chunk {
return &Chunk{
ID: hashString(text),
Height: 0,
Seq: seq,
Text: text,
Tokens: CountTokens(text),
Children: ChunkSlice{},
}
}
func (c *Chunk) String() string {
return fmt.Sprintf("%s:%d:%d:%d:%d", c.ID, c.Height, c.Seq, c.Tokens, len(c.Children))
}
type ChunkSlice []*Chunk
func (cs ChunkSlice) Tokens() int {
tokens := 0
for _, chunk := range cs {
tokens += chunk.Tokens
}
return tokens
}
func (cs ChunkSlice) Text() string {
var text string
for _, chunk := range cs {
text += chunk.Text + " "
}
return text
}
func (cs ChunkSlice) String() string {
heightMap := make(map[int]bool)
heights := []string{}
seqs := []string{}
for _, chunk := range cs {
seqs = append(seqs, fmt.Sprintf("%02d", chunk.Seq))
if _, ok := heightMap[chunk.Height]; !ok {
heightMap[chunk.Height] = true
heights = append(heights, fmt.Sprintf("%d", chunk.Height))
}
}
return fmt.Sprintf("Heights: %s, Seqs: %s, Chunks: %d, Tokens: %d",
strings.Join(heights, "_"), strings.Join(seqs, "_"), len(cs), cs.Tokens())
}