/
tools.go
418 lines (351 loc) · 9.25 KB
/
tools.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
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
package openai
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync"
)
// The toImagePath modifies the image path to reflect the copy number
// and additional suffixes if provided. It resolves relative paths,
// and replaces ~ with the home directory path. If the provided path
// is a directory, it generates a unique filename with a .png extension.
func toImagePath(copy int, path string, sep ...string) (string, error) {
// Resolve ~ to the user's home directory.
if strings.HasPrefix(path, "~/") {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
path = filepath.Join(home, path[2:])
}
// Resolve relative paths to absolute paths.
absolutePath, err := filepath.Abs(path)
if err != nil {
return "", err
}
if strings.HasSuffix(absolutePath, "/") ||
strings.HasSuffix(absolutePath, "\\") ||
!strings.HasSuffix(absolutePath, ".png") {
// Check if the provided path is a directory
info, err := os.Stat(absolutePath)
if err != nil {
return "", err
}
if info.IsDir() {
// If the path is a directory, generate a unique filename
file, err := generateUniqueFilename()
if err != nil {
return "", err
}
return filepath.Join(absolutePath, file+".png"), nil
}
}
// Get file extension.
ext := filepath.Ext(absolutePath)
// File name without extension.
file := strings.TrimSuffix(filepath.Base(absolutePath), ext)
// File path without file name.
dir := filepath.Dir(absolutePath)
if len(sep) == 0 {
sep = []string{"_"}
}
// Build a new name with optional separators
for _, s := range sep {
file += s
}
if copy != 0 {
file += strconv.Itoa(copy)
}
file += ext
return filepath.Join(dir, file), nil
}
// The generateUniqueFilename generates a unique filename using
// the crypto/rand package from the Go standard library.
//
// Don't to use third-party libraries, for example github.com/google/uuid.
func generateUniqueFilename() (string, error) {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
return "", err
}
uuid := fmt.Sprintf("%x", b)
return uuid, nil
}
func saveByURL(path string, parallelTasks int, items []string) error {
var wg sync.WaitGroup
var errors []error
var errMutex sync.Mutex
// Create a semaphore with a maximum count of parallelTasks.
sem := make(chan struct{}, parallelTasks)
for i, item := range items {
// Increment waitgroup counter.
wg.Add(1)
// Acquire a token.
sem <- struct{}{}
go func(i int, item string) {
// Release token when done.
defer func() { <-sem; wg.Done() }()
p, err := toImagePath(i, path)
if err != nil {
errMutex.Lock()
errors = append(errors, err)
errMutex.Unlock()
return
}
resp, err := http.Get(item)
if err != nil {
errMutex.Lock()
errors = append(errors, err)
errMutex.Unlock()
return
}
defer resp.Body.Close()
out, err := os.Create(p)
if err != nil {
errMutex.Lock()
errors = append(errors, err)
errMutex.Unlock()
return
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
errMutex.Lock()
errors = append(errors, err)
errMutex.Unlock()
return
}
}(i, item)
}
// Wait for all goroutines to finish.
wg.Wait()
if len(errors) > 0 {
return errors[0]
}
return nil
}
func saveByBase64(path string, parallelTasks int, items []string) error {
var wg sync.WaitGroup
var errors []error
var errMutex sync.Mutex
// Create a semaphore with a maximum count of parallelTasks.
sem := make(chan struct{}, parallelTasks)
for i, item := range items {
// Increment waitgroup counter.
wg.Add(1)
// Acquire a token.
sem <- struct{}{}
go func(i int, item string) {
// Release token when done.
defer func() { <-sem; wg.Done() }()
// Convert base64 to bytes
dec, err := base64.StdEncoding.DecodeString(item)
if err != nil {
errMutex.Lock()
errors = append(errors, err)
errMutex.Unlock()
return
}
p, err := toImagePath(i, path)
if err != nil {
errMutex.Lock()
errors = append(errors, err)
errMutex.Unlock()
return
}
// Write bytes to file
err = ioutil.WriteFile(p, dec, 0o644)
if err != nil {
errMutex.Lock()
errors = append(errors, err)
errMutex.Unlock()
return
}
}(i, item)
}
// Wait for all goroutines to finish.
wg.Wait()
if len(errors) > 0 {
return errors[0]
}
return nil
}
// The urlBuild constructs a URL from a base URL as prefix
// (like: https://some.site/) and an endpoint (or path parts).
// The function returns an error as the second value if the URL is invalid.
func urlBuild(baseURL string, pathParts ...string) (string, error) {
u, err := url.Parse(baseURL)
if err != nil {
return "", err
}
u.Path = path.Join(u.Path, path.Join(pathParts...))
return u.String(), nil
}
// The isSuccessfulCode checks if the HTTP status code is successful.
func isSuccessfulCode(statusCode int) bool {
// Different endpoints has different successful status code,
// it can be: 200, 202, 204 etc.
return statusCode >= http.StatusOK && statusCode < http.StatusBadRequest
}
// The newJsonRequest creates a new HTTP request instance.
func newJsonRequest(c Clienter, m, u string, b any) (*http.Request, error) {
var body io.Reader
// Create a request body if it is passed.
if b != nil {
tmp, err := json.Marshal(b)
if err != nil {
return &http.Request{}, err
}
body = bytes.NewBuffer(tmp)
}
// Create a new HTTP request.
req, err := http.NewRequestWithContext(c.Context(), m, u, body)
if err != nil {
return req, err
}
// Set the request headers.
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.APIKey()))
if orgID := c.OrgID(); orgID != "" {
req.Header.Set("OpenAI-Organization", orgID)
}
// Add additional headers.
for k, values := range c.HTTPHeaders() {
for _, v := range values {
req.Header.Add(k, v)
}
}
return req, nil
}
func newDataRequest(c Clienter, m, u string, b any) (*http.Request, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// Use reflection to get the Value and Type of the request
// Indirect handles both pointers and values
val := reflect.Indirect(reflect.ValueOf(b))
typ := val.Type()
// Iterate over the fields of the request
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
typeField := typ.Field(i)
tag := typeField.Tag
// Skip fields without json tag
jsonTag := tag.Get("json")
if jsonTag == "" {
continue
}
// Split the tag and use the first part (before omitempty, if present).
jsonFieldName := strings.Split(jsonTag, ",")[0]
if field.Type().String() == "*os.File" {
file, ok := field.Interface().(*os.File)
if ok && file != nil {
fieldWriter, err := writer.CreateFormFile(
jsonFieldName,
filepath.Base(file.Name()),
)
if err != nil {
return &http.Request{}, err
}
_, err = io.Copy(fieldWriter, file)
if err != nil {
return &http.Request{}, err
}
}
} else {
// Check if the field is of type string
if field.Kind() == reflect.String {
err := writer.WriteField(jsonFieldName, field.String())
if err != nil {
return &http.Request{}, err
}
} else {
jsonField, err := json.Marshal(field.Interface())
if err != nil {
return &http.Request{}, err
}
err = writer.WriteField(jsonFieldName, string(jsonField))
if err != nil {
return &http.Request{}, err
}
}
}
}
err := writer.Close()
if err != nil {
return &http.Request{}, err
}
req, err := http.NewRequestWithContext(c.Context(), m, u, body)
if err != nil {
return &http.Request{}, err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.APIKey()))
if orgID := c.OrgID(); orgID != "" {
req.Header.Set("OpenAI-Organization", orgID)
}
return req, err
}
// The doRequest performs an HTTP request and returns
// the response body as a byte slice.
func doRequest(
c Clienter,
req *http.Request,
goal any,
) ([]byte, error) {
// Send request.
resp, err := c.HTTPClient().Do(req)
if err != nil {
netErr, ok := err.(net.Error)
if ok && netErr.Timeout() {
return []byte{}, ErrRequestTimedOut
}
return []byte{}, err
}
defer resp.Body.Close()
// Check the HTTP status code.
if !isSuccessfulCode(resp.StatusCode) {
// Read the response errorBody.
errorBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, fmt.Errorf("failed to read error body: %v", err)
}
errorResponse := ErrorResponse{}
json.Unmarshal(errorBody, &errorResponse)
// Return an error that includes the status code and the error details.
return []byte{}, fmt.Errorf(
"non-success status code %d: %s",
resp.StatusCode,
errorResponse.Error.Message,
)
}
// Read response body.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, err
}
// Unmarshal response body if goal is not nil and is a pointer to a struct.
if goal != nil &&
reflect.ValueOf(goal).Kind() == reflect.Ptr &&
reflect.Indirect(reflect.ValueOf(goal)).Kind() == reflect.Struct {
err = json.Unmarshal(body, goal)
if err != nil {
return []byte{}, err
}
}
return body, nil
}