-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbing-dalle3.go
238 lines (210 loc) · 5.51 KB
/
bing-dalle3.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
package bingdalle3
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
)
const (
UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
Timeout = 5 * time.Second
PageUrl = "https://www.bing.com/images/create"
ResultUrl = "https://www.bing.com/images/create/async/results/"
)
type BingDalle3 struct {
cookie string
}
func (bing *BingDalle3) genUrlForCreatingImage(prompt string) (string, error) {
fullUrl, err := url.Parse(PageUrl)
if err != nil {
return "", err
}
queryParams := url.Values{}
queryParams.Add("q", prompt)
queryParams.Add("rt", "4")
queryParams.Add("FORM", "GENCRE")
fullUrl.RawQuery = queryParams.Encode()
return fullUrl.String(), nil
}
func (bing *BingDalle3) genUrlForQueryingResult(id string, prompt string) (string, error) {
fullUrlString, err := url.JoinPath(ResultUrl, id)
if err != nil {
return "", err
}
fullUrl, err := url.Parse(fullUrlString)
if err != nil {
return "", err
}
queryParams := url.Values{}
queryParams.Add("q", prompt)
fullUrl.RawQuery = queryParams.Encode()
return fullUrl.String(), nil
}
func (bing *BingDalle3) genUrlForQueryingResultReferer(id string, prompt string) (string, error) {
fullUrl, err := url.Parse(PageUrl)
if err != nil {
return "", err
}
queryParams := url.Values{}
queryParams.Add("q", prompt)
queryParams.Add("rt", "4")
queryParams.Add("FORM", "GENCRE")
queryParams.Add("id", id)
fullUrl.RawQuery = queryParams.Encode()
return fullUrl.String(), nil
}
func (bing *BingDalle3) GetTokenBalance() (int, error) {
req, err := http.NewRequest(http.MethodGet, PageUrl, nil)
if err != nil {
return 0, err
}
req.Header.Set("Cookie", bing.cookie)
req.Header.Set("User-Agent", UserAgent)
client := http.Client{Timeout: Timeout}
resp, err := client.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("resp status error: %s", resp.Status)
}
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return 0, err
}
value, err := strconv.Atoi(doc.Find("div#token_bal").Text())
if err != nil {
return 0, err
}
return value, nil
}
func (bing *BingDalle3) CreateImage(prompt string) (string, error) {
fullUrl, err := bing.genUrlForCreatingImage(prompt)
if err != nil {
return "", err
}
data := url.Values{}
data.Set("q", prompt)
data.Set("qs", "ds")
req, err := http.NewRequest(http.MethodPost, fullUrl, strings.NewReader(data.Encode()))
if err != nil {
return "", err
}
req.Header.Set("Cookie", bing.cookie)
req.Header.Set("User-Agent", UserAgent)
req.Header.Set("Referer", fullUrl)
client := http.Client{
Timeout: Timeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode == http.StatusOK {
errMsg := doc.Find("div.gil_err_sbt").Text()
return "", errors.New(errMsg)
} else if resp.StatusCode != http.StatusFound {
return "", fmt.Errorf("resp status error: %s", resp.Status)
}
redirectUrl, err := url.Parse(resp.Header.Get("Location"))
if err != nil {
return "", err
}
id := redirectUrl.Query().Get("id")
if id == "" {
return "", fmt.Errorf("ID not found in redirect URL: %s", redirectUrl.String())
}
return id, nil
}
func (bing *BingDalle3) QueryResult(id string, prompt string) ([]string, error) {
reqUrl, err := bing.genUrlForQueryingResult(id, prompt)
if err != nil {
return nil, err
}
referUrl, err := bing.genUrlForQueryingResultReferer(id, prompt)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodGet, reqUrl, nil)
if err != nil {
return nil, err
}
req.Header.Set("Cookie", bing.cookie)
req.Header.Set("User-Agent", UserAgent)
req.Header.Set("Referer", referUrl)
client := http.Client{Timeout: Timeout}
timeoutChan := time.After(10 * time.Minute)
ticker := time.NewTicker(2 * time.Second)
var urls []string
for {
select {
case <-timeoutChan:
return nil, errors.New("timeout")
case <-ticker.C:
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("resp status error: %s", resp.Status)
}
doc.Find("img.mimg").Each(func(i int, selection *goquery.Selection) {
url, _ := selection.Attr("src")
urls = append(urls, removeQueryParamsForUrl(url))
})
if len(urls) > 0 {
return urls, nil
}
}
}
}
func (bing *BingDalle3) DownloadImage(imageUrl string) (*[]byte, error) {
req, err := http.NewRequest(http.MethodGet, imageUrl, nil)
if err != nil {
return nil, err
}
req.Header.Set("Cookie", bing.cookie)
req.Header.Set("User-Agent", UserAgent)
req.Header.Set("Referer", PageUrl)
client := http.Client{Timeout: Timeout}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
content, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return &content, err
}
func NewBingDalle3(cookie string) *BingDalle3 {
return &BingDalle3{cookie: cookie}
}
func removeQueryParamsForUrl(fullUrl string) string {
url, err := url.Parse(fullUrl)
if err != nil {
return fullUrl
}
url.RawQuery = ""
return url.String()
}