-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathvideo.go
514 lines (448 loc) · 14.7 KB
/
video.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
package controller
import (
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"genspark2api/common"
"genspark2api/common/config"
logger "genspark2api/common/loggger"
"genspark2api/model"
"github.com/deanxv/CycleTLS/cycletls"
"github.com/gin-gonic/gin"
"github.com/samber/lo"
"io"
"net/http"
"strings"
"time"
)
func VideosForOpenAI(c *gin.Context) {
client := cycletls.Init()
defer safeClose(client)
var openAIReq model.VideosGenerationRequest
if err := c.BindJSON(&openAIReq); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if lo.Contains(common.VideoModelList, openAIReq.Model) == false {
c.JSON(400, gin.H{"error": "Invalid model"})
return
}
resp, err := VideoProcess(c, client, openAIReq)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("VideoProcess err %v\n", err))
c.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: err.Error(),
Type: "request_error",
Code: "500",
},
})
return
} else {
c.JSON(200, resp)
}
}
func VideoProcess(c *gin.Context, client cycletls.CycleTLS, openAIReq model.VideosGenerationRequest) (*model.VideosGenerationResponse, error) {
const (
errNoValidCookies = "No valid cookies available"
errServerErrMsg = "An error occurred with the current request, please try again"
errNoValidTaskIDs = "No valid task IDs received"
)
var (
maxRetries int
cookie string
chatId string
)
cookieManager := config.NewCookieManager()
ctx := c.Request.Context()
// Initialize session manager and get initial cookie
if len(config.SessionImageChatMap) == 0 {
//logger.Warnf(ctx, "未配置环境变量 SESSION_IMAGE_CHAT_MAP, 可能会生图失败!")
maxRetries = len(cookieManager.Cookies)
var err error
cookie, err = cookieManager.GetRandomCookie()
if err != nil {
logger.Errorf(ctx, "Failed to get initial cookie: %v", err)
return nil, fmt.Errorf(errNoValidCookies)
}
}
for attempt := 0; attempt < maxRetries; attempt++ {
// Create request body
requestBody, err := createVideoRequestBody(c, cookie, &openAIReq, chatId)
if err != nil {
logger.Errorf(ctx, "Failed to create request body: %v", err)
return nil, err
}
// Marshal request body
jsonData, err := json.Marshal(requestBody)
if err != nil {
logger.Errorf(ctx, "Failed to marshal request body: %v", err)
return nil, err
}
// Make request
response, err := makeVideoRequest(client, jsonData, cookie)
if err != nil {
logger.Errorf(ctx, "Failed to make video request: %v", err)
return nil, err
}
body := response.Body
switch {
case common.IsRateLimit(body):
logger.Warnf(ctx, "Cookie rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
config.AddRateLimitCookie(cookie, time.Now().Add(time.Duration(config.RateLimitCookieLockDuration)*time.Second))
cookie, err = cookieManager.GetNextCookie()
if err != nil {
logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
return nil, fmt.Errorf(errNoValidCookies)
}
continue
case common.IsFreeLimit(body):
logger.Warnf(ctx, "Cookie free rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
config.AddRateLimitCookie(cookie, time.Now().Add(24*60*60*time.Second))
cookie, err = cookieManager.GetNextCookie()
if err != nil {
logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
return nil, fmt.Errorf(errNoValidCookies)
}
continue
case common.IsNotLogin(body):
logger.Warnf(ctx, "Cookie Not Login, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
cookie, err = cookieManager.GetNextCookie()
if err != nil {
logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
return nil, fmt.Errorf(errNoValidCookies)
}
continue
case common.IsServerError(body):
logger.Errorf(ctx, errServerErrMsg)
return nil, fmt.Errorf(errServerErrMsg)
case common.IsServerOverloaded(body):
logger.Errorf(ctx, fmt.Sprintf("Server overloaded, please try again later.%s", "官方服务超载"))
return nil, fmt.Errorf("Server overloaded, please try again later.")
}
projectId, taskIDs := extractVideoTaskIDs(response.Body)
if len(taskIDs) == 0 {
logger.Errorf(ctx, "Response body: %s", response.Body)
return nil, fmt.Errorf(errNoValidTaskIDs)
}
// Poll for image URLs
imageURLs := pollVideoTaskStatus(c, client, taskIDs, cookie)
if len(imageURLs) == 0 {
logger.Warnf(ctx, "No image URLs received, retrying with next cookie")
continue
}
// Create response object
result := &model.VideosGenerationResponse{
Created: time.Now().Unix(),
Data: make([]*model.VideosGenerationDataResponse, 0, len(imageURLs)),
}
// Process image URLs
for _, url := range imageURLs {
data := &model.VideosGenerationDataResponse{
URL: url,
RevisedPrompt: openAIReq.Prompt,
}
//if openAIReq.ResponseFormat == "b64_json" {
// base64Str, err := getBase64ByUrl(data.URL)
// if err != nil {
// logger.Errorf(ctx, "getBase64ByUrl error: %v", err)
// continue
// }
// data.B64Json = "data:image/webp;base64," + base64Str
//}
result.Data = append(result.Data, data)
}
// Handle successful case
if len(result.Data) > 0 {
// Delete temporary session if needed
if config.AutoDelChat == 1 {
go func() {
client := cycletls.Init()
defer safeClose(client)
makeDeleteRequest(client, cookie, projectId)
}()
}
return result, nil
}
}
// All retries exhausted
logger.Errorf(ctx, "All cookies exhausted after %d attempts", maxRetries)
return nil, fmt.Errorf("all cookies are temporarily unavailable")
}
func createVideoRequestBody(c *gin.Context, cookie string, openAIReq *model.VideosGenerationRequest, chatId string) (map[string]interface{}, error) {
// 创建模型配置
modelConfigs := []map[string]interface{}{
{
"model": openAIReq.Model,
"aspect_ratio": openAIReq.AspectRatio,
"reflection_enabled": openAIReq.AutoPrompt,
"duration": openAIReq.Duration,
},
}
// 创建消息数组
var messages []map[string]interface{}
if openAIReq.Image != "" {
var base64Data string
if strings.HasPrefix(openAIReq.Image, "http://") || strings.HasPrefix(openAIReq.Image, "https://") {
// 下载文件
bytes, err := fetchImageBytes(openAIReq.Image)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("fetchImageBytes err %v\n", err))
return nil, fmt.Errorf("fetchImageBytes err %v\n", err)
}
contentType := http.DetectContentType(bytes)
if strings.HasPrefix(contentType, "image/") {
// 是图片类型,转换为base64
base64Data = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(bytes)
}
} else if common.IsImageBase64(openAIReq.Image) {
// 如果已经是 base64 格式
if !strings.HasPrefix(openAIReq.Image, "data:image") {
base64Data = "data:image/jpeg;base64," + openAIReq.Image
} else {
base64Data = openAIReq.Image
}
}
// 构建包含图片的消息
if base64Data != "" {
messages = []map[string]interface{}{
{
"role": "user",
"content": []map[string]interface{}{
{
"type": "image_url",
"image_url": map[string]interface{}{
"url": base64Data,
},
},
{
"type": "text",
"text": openAIReq.Prompt,
},
},
},
}
}
}
// 如果没有图片或处理图片失败,使用纯文本消息
if len(messages) == 0 {
messages = []map[string]interface{}{
{
"role": "user",
"content": openAIReq.Prompt,
},
}
}
var currentQueryString string
if len(chatId) != 0 {
currentQueryString = fmt.Sprintf("id=%s&type=%s", chatId, videoType)
} else {
currentQueryString = fmt.Sprintf("type=%s", videoType)
}
// 创建请求体
requestBody := map[string]interface{}{
"type": "COPILOT_MOA_VIDEO",
//"current_query_string": "type=COPILOT_MOA_IMAGE",
"current_query_string": currentQueryString,
"messages": messages,
"user_s_input": openAIReq.Prompt,
"action_params": map[string]interface{}{},
"extra_data": map[string]interface{}{
"model_configs": modelConfigs,
"imageModelMap": map[string]interface{}{},
},
}
logger.Debug(c.Request.Context(), fmt.Sprintf("RequestBody: %v", requestBody))
if strings.TrimSpace(config.RecaptchaProxyUrl) == "" ||
(!strings.HasPrefix(config.RecaptchaProxyUrl, "http://") &&
!strings.HasPrefix(config.RecaptchaProxyUrl, "https://")) {
return requestBody, nil
} else {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
// 检查并补充 RecaptchaProxyUrl 的末尾斜杠
if !strings.HasSuffix(config.RecaptchaProxyUrl, "/") {
config.RecaptchaProxyUrl += "/"
}
// 创建请求
req, err := http.NewRequest("GET", fmt.Sprintf("%sgenspark", config.RecaptchaProxyUrl), nil)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("创建/genspark请求失败 %v\n", err))
return nil, err
}
// 设置请求头
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Cookie", cookie)
// 发送请求
resp, err := client.Do(req)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("发送/genspark请求失败 %v\n", err))
return nil, err
}
defer resp.Body.Close()
// 读取响应体
body, err := io.ReadAll(resp.Body)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("读取/genspark响应失败 %v\n", err))
return nil, err
}
type Response struct {
Code int `json:"code"`
Token string `json:"token"`
Message string `json:"message"`
}
if resp.StatusCode == 200 {
var response Response
if err := json.Unmarshal(body, &response); err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("读取/genspark JSON 失败 %v\n", err))
return nil, err
}
if response.Code == 200 {
logger.Debugf(c.Request.Context(), fmt.Sprintf("g_recaptcha_token: %v\n", response.Token))
requestBody["g_recaptcha_token"] = response.Token
logger.Infof(c.Request.Context(), fmt.Sprintf("cheat success!"))
return requestBody, nil
} else {
logger.Errorf(c.Request.Context(), fmt.Sprintf("读取/genspark token 失败 %v\n", err))
return nil, err
}
} else {
logger.Errorf(c.Request.Context(), fmt.Sprintf("请求/genspark失败 %v\n", err))
return nil, err
}
}
}
func makeVideoRequest(client cycletls.CycleTLS, jsonData []byte, cookie string) (cycletls.Response, error) {
accept := "*/*"
return client.Do(apiEndpoint, cycletls.Options{
UserAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
Timeout: 10 * 60 * 60,
Proxy: config.ProxyUrl, // 在每个请求中设置代理
Body: string(jsonData),
Method: "POST",
Headers: map[string]string{
"Content-Type": "application/json",
"Accept": accept,
"Origin": baseURL,
"Referer": baseURL + "/",
"Cookie": cookie,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
},
}, "POST")
}
func extractVideoTaskIDs(responseBody string) (string, []string) {
var taskIDs []string
var projectId string
// 分行处理响应
lines := strings.Split(responseBody, "\n")
for _, line := range lines {
// 找到包含project_id的行
if strings.Contains(line, "project_start") {
// 去掉"data: "前缀
jsonStr := strings.TrimPrefix(line, "data: ")
// 解析JSON
var jsonResp struct {
ProjectID string `json:"id"`
}
if err := json.Unmarshal([]byte(jsonStr), &jsonResp); err != nil {
continue
}
// 保存project_id
projectId = jsonResp.ProjectID
}
// 找到包含task_id的行
if strings.Contains(line, "task_id") {
// 去掉"data: "前缀
jsonStr := strings.TrimPrefix(line, "data: ")
// 解析外层JSON
var outerJSON struct {
Content string `json:"content"`
}
if err := json.Unmarshal([]byte(jsonStr), &outerJSON); err != nil {
continue
}
// 解析内层JSON (content字段)
var innerJSON struct {
GeneratedVideos []struct {
TaskID string `json:"task_id"`
} `json:"generated_videos"`
}
if err := json.Unmarshal([]byte(outerJSON.Content), &innerJSON); err != nil {
continue
}
// 提取所有task_id
for _, img := range innerJSON.GeneratedVideos {
if img.TaskID != "" {
taskIDs = append(taskIDs, img.TaskID)
}
}
}
}
return projectId, taskIDs
}
func pollVideoTaskStatus(c *gin.Context, client cycletls.CycleTLS, taskIDs []string, cookie string) []string {
var imageURLs []string
requestData := map[string]interface{}{
"task_ids": taskIDs,
}
jsonData, err := json.Marshal(requestData)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to marshal request data"})
return imageURLs
}
sseChan, err := client.DoSSE("https://www.genspark.ai/api/vg_tasks_status", cycletls.Options{
Timeout: 10 * 60 * 60,
Proxy: config.ProxyUrl, // 在每个请求中设置代理
Body: string(jsonData),
Method: "POST",
Headers: map[string]string{
"Content-Type": "application/json",
"Accept": "*/*",
"Origin": baseURL,
"Referer": baseURL + "/",
"Cookie": cookie,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
},
}, "POST")
if err != nil {
logger.Errorf(c, "Failed to make stream request: %v", err)
return imageURLs
}
for response := range sseChan {
if response.Done {
//logger.Warnf(c.Request.Context(), response.Data)
return imageURLs
}
data := response.Data
if data == "" {
continue
}
logger.Debug(c.Request.Context(), strings.TrimSpace(data))
var responseData map[string]interface{}
if err := json.Unmarshal([]byte(data), &responseData); err != nil {
continue
}
if responseData["type"] == "TASKS_STATUS_COMPLETE" {
if finalStatus, ok := responseData["final_status"].(map[string]interface{}); ok {
for _, taskID := range taskIDs {
if task, exists := finalStatus[taskID].(map[string]interface{}); exists {
if status, ok := task["status"].(string); ok && status == "SUCCESS" {
if urls, ok := task["video_urls"].([]interface{}); ok && len(urls) > 0 {
if imageURL, ok := urls[0].(string); ok {
imageURLs = append(imageURLs, imageURL)
}
}
}
}
}
}
}
}
return imageURLs
}