-
Notifications
You must be signed in to change notification settings - Fork 42
/
csv.go
135 lines (111 loc) 路 2.42 KB
/
csv.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
package loader
import (
"context"
"encoding/csv"
"errors"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/henomis/lingoose/document"
"github.com/henomis/lingoose/types"
)
type CSVLoader struct {
separator rune
filename string
lazyQuotes bool
}
func NewCSVLoader(filename string) *CSVLoader {
return &CSVLoader{
filename: filename,
separator: ',',
}
}
func NewCSV() *CSVLoader {
return &CSVLoader{
separator: ',',
}
}
func (c *CSVLoader) WithLazyQuotes() *CSVLoader {
c.lazyQuotes = true
return c
}
func (c *CSVLoader) WithSeparator(separator rune) *CSVLoader {
c.separator = separator
return c
}
//nolint:revive
func (c *CSVLoader) WithTextSplitter(textSplitter TextSplitter) *CSVLoader {
// can't split csv
return c
}
func (c *CSVLoader) Load(ctx context.Context) ([]document.Document, error) {
_ = ctx
err := c.validate()
if err != nil {
return nil, err
}
documents, err := c.readCSV()
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrInternal, err)
}
return documents, nil
}
func (c *CSVLoader) LoadFromSource(ctx context.Context, source string) ([]document.Document, error) {
c.filename = source
return c.Load(ctx)
}
func (c *CSVLoader) validate() error {
fileStat, err := os.Stat(c.filename)
if err != nil {
return fmt.Errorf("%w: %w", ErrInternal, err)
}
if fileStat.IsDir() {
return fmt.Errorf("%w: %w", ErrInternal, os.ErrNotExist)
}
return nil
}
func (c *CSVLoader) readCSV() ([]document.Document, error) {
csvFile, err := os.Open(c.filename)
if err != nil {
log.Fatal(err)
}
defer csvFile.Close()
reader := csv.NewReader(csvFile)
reader.Comma = c.separator
reader.LazyQuotes = c.lazyQuotes
var documents []document.Document
var titles []string
for {
record, errRead := reader.Read()
if errors.Is(errRead, io.EOF) {
break
}
if errRead != nil {
return nil, errRead
}
if titles == nil {
titles = make([]string, len(record))
for i, r := range record {
titles[i] = strings.ReplaceAll(r, "\"", "")
titles[i] = strings.TrimSpace(titles[i])
}
continue
}
var content string
for i, title := range titles {
value := strings.ReplaceAll(record[i], "\"", "")
value = strings.TrimSpace(value)
content += fmt.Sprintf("%s: %s", title, value)
content += "\n"
}
documents = append(documents, document.Document{
Content: content,
Metadata: types.Meta{
SourceMetadataKey: c.filename,
},
})
}
return documents, nil
}