adaptor.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. package vidu
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "time"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/gin-gonic/gin"
  12. "github.com/QuantumNous/new-api/constant"
  13. "github.com/QuantumNous/new-api/dto"
  14. "github.com/QuantumNous/new-api/model"
  15. "github.com/QuantumNous/new-api/relay/channel"
  16. relaycommon "github.com/QuantumNous/new-api/relay/common"
  17. "github.com/QuantumNous/new-api/service"
  18. "github.com/pkg/errors"
  19. )
  20. // ============================
  21. // Request / Response structures
  22. // ============================
  23. type requestPayload struct {
  24. Model string `json:"model"`
  25. Images []string `json:"images"`
  26. Prompt string `json:"prompt,omitempty"`
  27. Duration int `json:"duration,omitempty"`
  28. Seed int `json:"seed,omitempty"`
  29. Resolution string `json:"resolution,omitempty"`
  30. MovementAmplitude string `json:"movement_amplitude,omitempty"`
  31. Bgm bool `json:"bgm,omitempty"`
  32. Payload string `json:"payload,omitempty"`
  33. CallbackUrl string `json:"callback_url,omitempty"`
  34. }
  35. type responsePayload struct {
  36. TaskId string `json:"task_id"`
  37. State string `json:"state"`
  38. Model string `json:"model"`
  39. Images []string `json:"images"`
  40. Prompt string `json:"prompt"`
  41. Duration int `json:"duration"`
  42. Seed int `json:"seed"`
  43. Resolution string `json:"resolution"`
  44. Bgm bool `json:"bgm"`
  45. MovementAmplitude string `json:"movement_amplitude"`
  46. Payload string `json:"payload"`
  47. CreatedAt string `json:"created_at"`
  48. }
  49. type taskResultResponse struct {
  50. State string `json:"state"`
  51. ErrCode string `json:"err_code"`
  52. Credits int `json:"credits"`
  53. Payload string `json:"payload"`
  54. Creations []creation `json:"creations"`
  55. }
  56. type creation struct {
  57. ID string `json:"id"`
  58. URL string `json:"url"`
  59. CoverURL string `json:"cover_url"`
  60. }
  61. // ============================
  62. // Adaptor implementation
  63. // ============================
  64. type TaskAdaptor struct {
  65. ChannelType int
  66. baseURL string
  67. }
  68. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  69. a.ChannelType = info.ChannelType
  70. a.baseURL = info.ChannelBaseUrl
  71. }
  72. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) *dto.TaskError {
  73. if err := relaycommon.ValidateBasicTaskRequest(c, info, constant.TaskActionGenerate); err != nil {
  74. return err
  75. }
  76. req, err := relaycommon.GetTaskRequest(c)
  77. if err != nil {
  78. return service.TaskErrorWrapper(err, "get_task_request_failed", http.StatusBadRequest)
  79. }
  80. action := constant.TaskActionTextGenerate
  81. if meatAction, ok := req.Metadata["action"]; ok {
  82. action, _ = meatAction.(string)
  83. } else if req.HasImage() {
  84. action = constant.TaskActionGenerate
  85. if info.ChannelType == constant.ChannelTypeVidu {
  86. // vidu 增加 首尾帧生视频和参考图生视频
  87. if len(req.Images) == 2 {
  88. action = constant.TaskActionFirstTailGenerate
  89. } else if len(req.Images) > 2 {
  90. action = constant.TaskActionReferenceGenerate
  91. }
  92. }
  93. }
  94. info.Action = action
  95. return nil
  96. }
  97. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  98. v, exists := c.Get("task_request")
  99. if !exists {
  100. return nil, fmt.Errorf("request not found in context")
  101. }
  102. req := v.(relaycommon.TaskSubmitReq)
  103. body, err := a.convertToRequestPayload(&req)
  104. if err != nil {
  105. return nil, err
  106. }
  107. if info.Action == constant.TaskActionReferenceGenerate {
  108. if strings.Contains(body.Model, "viduq2") {
  109. // 参考图生视频只能用 viduq2 模型, 不能带有pro或turbo后缀 https://platform.vidu.cn/docs/reference-to-video
  110. body.Model = "viduq2"
  111. }
  112. }
  113. data, err := json.Marshal(body)
  114. if err != nil {
  115. return nil, err
  116. }
  117. return bytes.NewReader(data), nil
  118. }
  119. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  120. var path string
  121. switch info.Action {
  122. case constant.TaskActionGenerate:
  123. path = "/img2video"
  124. case constant.TaskActionFirstTailGenerate:
  125. path = "/start-end2video"
  126. case constant.TaskActionReferenceGenerate:
  127. path = "/reference2video"
  128. default:
  129. path = "/text2video"
  130. }
  131. return fmt.Sprintf("%s/ent/v2%s", a.baseURL, path), nil
  132. }
  133. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  134. req.Header.Set("Content-Type", "application/json")
  135. req.Header.Set("Accept", "application/json")
  136. req.Header.Set("Authorization", "Token "+info.ApiKey)
  137. return nil
  138. }
  139. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  140. return channel.DoTaskApiRequest(a, c, info, requestBody)
  141. }
  142. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  143. responseBody, err := io.ReadAll(resp.Body)
  144. if err != nil {
  145. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  146. return
  147. }
  148. var vResp responsePayload
  149. err = json.Unmarshal(responseBody, &vResp)
  150. if err != nil {
  151. taskErr = service.TaskErrorWrapper(errors.Wrap(err, fmt.Sprintf("%s", responseBody)), "unmarshal_response_failed", http.StatusInternalServerError)
  152. return
  153. }
  154. if vResp.State == "failed" {
  155. taskErr = service.TaskErrorWrapperLocal(fmt.Errorf("task failed"), "task_failed", http.StatusBadRequest)
  156. return
  157. }
  158. ov := dto.NewOpenAIVideo()
  159. ov.ID = vResp.TaskId
  160. ov.TaskID = vResp.TaskId
  161. ov.CreatedAt = time.Now().Unix()
  162. ov.Model = info.OriginModelName
  163. c.JSON(http.StatusOK, ov)
  164. return vResp.TaskId, responseBody, nil
  165. }
  166. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  167. taskID, ok := body["task_id"].(string)
  168. if !ok {
  169. return nil, fmt.Errorf("invalid task_id")
  170. }
  171. url := fmt.Sprintf("%s/ent/v2/tasks/%s/creations", baseUrl, taskID)
  172. req, err := http.NewRequest(http.MethodGet, url, nil)
  173. if err != nil {
  174. return nil, err
  175. }
  176. req.Header.Set("Accept", "application/json")
  177. req.Header.Set("Authorization", "Token "+key)
  178. client, err := service.GetHttpClientWithProxy(proxy)
  179. if err != nil {
  180. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  181. }
  182. return client.Do(req)
  183. }
  184. func (a *TaskAdaptor) GetModelList() []string {
  185. return []string{"viduq2", "viduq1", "vidu2.0", "vidu1.5"}
  186. }
  187. func (a *TaskAdaptor) GetChannelName() string {
  188. return "vidu"
  189. }
  190. // ============================
  191. // helpers
  192. // ============================
  193. func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*requestPayload, error) {
  194. r := requestPayload{
  195. Model: defaultString(req.Model, "viduq1"),
  196. Images: req.Images,
  197. Prompt: req.Prompt,
  198. Duration: defaultInt(req.Duration, 5),
  199. Resolution: defaultString(req.Size, "1080p"),
  200. MovementAmplitude: "auto",
  201. Bgm: false,
  202. }
  203. metadata := req.Metadata
  204. medaBytes, err := json.Marshal(metadata)
  205. if err != nil {
  206. return nil, errors.Wrap(err, "metadata marshal metadata failed")
  207. }
  208. err = json.Unmarshal(medaBytes, &r)
  209. if err != nil {
  210. return nil, errors.Wrap(err, "unmarshal metadata failed")
  211. }
  212. return &r, nil
  213. }
  214. func defaultString(value, defaultValue string) string {
  215. if value == "" {
  216. return defaultValue
  217. }
  218. return value
  219. }
  220. func defaultInt(value, defaultValue int) int {
  221. if value == 0 {
  222. return defaultValue
  223. }
  224. return value
  225. }
  226. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  227. taskInfo := &relaycommon.TaskInfo{}
  228. var taskResp taskResultResponse
  229. err := json.Unmarshal(respBody, &taskResp)
  230. if err != nil {
  231. return nil, errors.Wrap(err, "failed to unmarshal response body")
  232. }
  233. state := taskResp.State
  234. switch state {
  235. case "created", "queueing":
  236. taskInfo.Status = model.TaskStatusSubmitted
  237. case "processing":
  238. taskInfo.Status = model.TaskStatusInProgress
  239. case "success":
  240. taskInfo.Status = model.TaskStatusSuccess
  241. if len(taskResp.Creations) > 0 {
  242. taskInfo.Url = taskResp.Creations[0].URL
  243. }
  244. case "failed":
  245. taskInfo.Status = model.TaskStatusFailure
  246. if taskResp.ErrCode != "" {
  247. taskInfo.Reason = taskResp.ErrCode
  248. }
  249. default:
  250. return nil, fmt.Errorf("unknown task state: %s", state)
  251. }
  252. return taskInfo, nil
  253. }
  254. func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, error) {
  255. var viduResp taskResultResponse
  256. if err := json.Unmarshal(originTask.Data, &viduResp); err != nil {
  257. return nil, errors.Wrap(err, "unmarshal vidu task data failed")
  258. }
  259. openAIVideo := dto.NewOpenAIVideo()
  260. openAIVideo.ID = originTask.TaskID
  261. openAIVideo.Status = originTask.Status.ToVideoStatus()
  262. openAIVideo.SetProgressStr(originTask.Progress)
  263. openAIVideo.CreatedAt = originTask.CreatedAt
  264. openAIVideo.CompletedAt = originTask.UpdatedAt
  265. if len(viduResp.Creations) > 0 && viduResp.Creations[0].URL != "" {
  266. openAIVideo.SetMetadata("url", viduResp.Creations[0].URL)
  267. }
  268. if viduResp.State == "failed" && viduResp.ErrCode != "" {
  269. openAIVideo.Error = &dto.OpenAIVideoError{
  270. Message: viduResp.ErrCode,
  271. Code: viduResp.ErrCode,
  272. }
  273. }
  274. jsonData, _ := common.Marshal(openAIVideo)
  275. return jsonData, nil
  276. }