-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.go
65 lines (62 loc) · 2.04 KB
/
image.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
package sydney
import (
"errors"
"log/slog"
"net/url"
"regexp"
"strings"
"time"
"github.com/cphovo/ollm/util"
)
func (o *Sydney) GenerateImage(generativeImage GenerativeImage) (GenerateImageResult, error) {
start := time.Now()
var empty GenerateImageResult
_, client, err := util.MakeHTTPClient(o.proxy, 15*time.Second)
if err != nil {
return empty, err
}
client.SetCommonHeader("Referer", "https://www.bing.com/search?q=Bing+AI&showconv=1&wlexpsignin=1").
SetCommonHeader("Cookie", util.FormatCookieString(o.cookies))
resp, err := client.R().Get(generativeImage.URL)
if err != nil {
return empty, err
}
// arr := regexp.MustCompile("/images/create/async/results/(.*?)\\?").FindStringSubmatch(resp.String())
arr := regexp.MustCompile(`/images/create/async/results/(.*?)\?`).FindStringSubmatch(resp.String())
if len(arr) < 2 {
return empty, errors.New("cannot find image creation result")
}
resultID := arr[1]
re := regexp.MustCompile(`<img class="mimg".*?src="(.*?)"`)
u := "https://www.bing.com/images/create/async/results/" + resultID +
"?q=" + url.QueryEscape(generativeImage.Text) + "&partner=sydney&showselective=1&IID=images.as"
slog.Info("Result URL", "v", u)
for i := 0; i < 15; i++ {
time.Sleep(3 * time.Second)
resp, err := client.R().Get(u)
if err != nil {
return empty, err
}
bodyStr := resp.String()
if strings.Contains(bodyStr, "Please try again or come back later") {
return empty, errors.New("the prompt for image creation has been rejected by Bing")
}
var imageURLs []string
arr := re.FindAllStringSubmatch(bodyStr, -1)
if len(arr) == 0 {
slog.Info("No matched images currently", "body", bodyStr)
continue
}
for _, match := range arr {
imageURLs = append(imageURLs, match[1])
}
slog.Info("Created images successfully", "images", imageURLs)
return GenerateImageResult{
GenerativeImage: generativeImage,
ImageURLs: imageURLs,
Duration: time.Since(start),
// Duration: time.Now().Sub(start),
}, nil
}
return empty, errors.New("image creation timeout")
}