adaptor.go 8.2 KB

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