adaptor.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. package hailuo
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/QuantumNous/new-api/common"
  12. "github.com/QuantumNous/new-api/model"
  13. "github.com/gin-gonic/gin"
  14. "github.com/pkg/errors"
  15. "github.com/QuantumNous/new-api/constant"
  16. "github.com/QuantumNous/new-api/dto"
  17. "github.com/QuantumNous/new-api/relay/channel"
  18. relaycommon "github.com/QuantumNous/new-api/relay/common"
  19. "github.com/QuantumNous/new-api/service"
  20. )
  21. // https://platform.minimaxi.com/docs/api-reference/video-generation-intro
  22. type TaskAdaptor struct {
  23. ChannelType int
  24. apiKey string
  25. baseURL string
  26. }
  27. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  28. a.ChannelType = info.ChannelType
  29. a.baseURL = info.ChannelBaseUrl
  30. a.apiKey = info.ApiKey
  31. }
  32. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  33. return relaycommon.ValidateBasicTaskRequest(c, info, constant.TaskActionGenerate)
  34. }
  35. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  36. return fmt.Sprintf("%s%s", a.baseURL, TextToVideoEndpoint), nil
  37. }
  38. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  39. req.Header.Set("Content-Type", "application/json")
  40. req.Header.Set("Accept", "application/json")
  41. req.Header.Set("Authorization", "Bearer "+a.apiKey)
  42. return nil
  43. }
  44. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  45. v, exists := c.Get("task_request")
  46. if !exists {
  47. return nil, fmt.Errorf("request not found in context")
  48. }
  49. req, ok := v.(relaycommon.TaskSubmitReq)
  50. if !ok {
  51. return nil, fmt.Errorf("invalid request type in context")
  52. }
  53. body, err := a.convertToRequestPayload(&req)
  54. if err != nil {
  55. return nil, errors.Wrap(err, "convert request payload failed")
  56. }
  57. data, err := json.Marshal(body)
  58. if err != nil {
  59. return nil, err
  60. }
  61. return bytes.NewReader(data), nil
  62. }
  63. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  64. return channel.DoTaskApiRequest(a, c, info, requestBody)
  65. }
  66. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  67. responseBody, err := io.ReadAll(resp.Body)
  68. if err != nil {
  69. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  70. return
  71. }
  72. _ = resp.Body.Close()
  73. var hResp VideoResponse
  74. if err := json.Unmarshal(responseBody, &hResp); err != nil {
  75. taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
  76. return
  77. }
  78. if hResp.BaseResp.StatusCode != StatusSuccess {
  79. taskErr = service.TaskErrorWrapper(
  80. fmt.Errorf("hailuo api error: %s", hResp.BaseResp.StatusMsg),
  81. strconv.Itoa(hResp.BaseResp.StatusCode),
  82. http.StatusBadRequest,
  83. )
  84. return
  85. }
  86. ov := dto.NewOpenAIVideo()
  87. ov.ID = hResp.TaskID
  88. ov.TaskID = hResp.TaskID
  89. ov.CreatedAt = time.Now().Unix()
  90. ov.Model = info.OriginModelName
  91. c.JSON(http.StatusOK, ov)
  92. return hResp.TaskID, responseBody, nil
  93. }
  94. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  95. taskID, ok := body["task_id"].(string)
  96. if !ok {
  97. return nil, fmt.Errorf("invalid task_id")
  98. }
  99. uri := fmt.Sprintf("%s%s?task_id=%s", baseUrl, QueryTaskEndpoint, taskID)
  100. req, err := http.NewRequest(http.MethodGet, uri, nil)
  101. if err != nil {
  102. return nil, err
  103. }
  104. req.Header.Set("Accept", "application/json")
  105. req.Header.Set("Authorization", "Bearer "+key)
  106. client, err := service.GetHttpClientWithProxy(proxy)
  107. if err != nil {
  108. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  109. }
  110. return client.Do(req)
  111. }
  112. func (a *TaskAdaptor) GetModelList() []string {
  113. return ModelList
  114. }
  115. func (a *TaskAdaptor) GetChannelName() string {
  116. return ChannelName
  117. }
  118. func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*VideoRequest, error) {
  119. modelConfig := GetModelConfig(req.Model)
  120. duration := DefaultDuration
  121. if req.Duration > 0 {
  122. duration = req.Duration
  123. }
  124. resolution := modelConfig.DefaultResolution
  125. if req.Size != "" {
  126. resolution = a.parseResolutionFromSize(req.Size, modelConfig)
  127. }
  128. videoRequest := &VideoRequest{
  129. Model: req.Model,
  130. Prompt: req.Prompt,
  131. Duration: &duration,
  132. Resolution: resolution,
  133. }
  134. if err := req.UnmarshalMetadata(&videoRequest); err != nil {
  135. return nil, errors.Wrap(err, "unmarshal metadata to video request failed")
  136. }
  137. return videoRequest, nil
  138. }
  139. func (a *TaskAdaptor) parseResolutionFromSize(size string, modelConfig ModelConfig) string {
  140. switch {
  141. case strings.Contains(size, "1080"):
  142. return Resolution1080P
  143. case strings.Contains(size, "768"):
  144. return Resolution768P
  145. case strings.Contains(size, "720"):
  146. return Resolution720P
  147. case strings.Contains(size, "512"):
  148. return Resolution512P
  149. default:
  150. return modelConfig.DefaultResolution
  151. }
  152. }
  153. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  154. resTask := QueryTaskResponse{}
  155. if err := json.Unmarshal(respBody, &resTask); err != nil {
  156. return nil, errors.Wrap(err, "unmarshal task result failed")
  157. }
  158. taskResult := relaycommon.TaskInfo{}
  159. if resTask.BaseResp.StatusCode == StatusSuccess {
  160. taskResult.Code = 0
  161. } else {
  162. taskResult.Code = resTask.BaseResp.StatusCode
  163. taskResult.Reason = resTask.BaseResp.StatusMsg
  164. taskResult.Status = model.TaskStatusFailure
  165. taskResult.Progress = "100%"
  166. }
  167. switch resTask.Status {
  168. case TaskStatusPreparing, TaskStatusQueueing, TaskStatusProcessing:
  169. taskResult.Status = model.TaskStatusInProgress
  170. taskResult.Progress = "30%"
  171. if resTask.Status == TaskStatusProcessing {
  172. taskResult.Progress = "50%"
  173. }
  174. case TaskStatusSuccess:
  175. taskResult.Status = model.TaskStatusSuccess
  176. taskResult.Progress = "100%"
  177. taskResult.Url = a.buildVideoURL(resTask.TaskID, resTask.FileID)
  178. case TaskStatusFailed:
  179. taskResult.Status = model.TaskStatusFailure
  180. taskResult.Progress = "100%"
  181. if taskResult.Reason == "" {
  182. taskResult.Reason = "task failed"
  183. }
  184. default:
  185. taskResult.Status = model.TaskStatusInProgress
  186. taskResult.Progress = "30%"
  187. }
  188. return &taskResult, nil
  189. }
  190. func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, error) {
  191. var hailuoResp QueryTaskResponse
  192. if err := json.Unmarshal(originTask.Data, &hailuoResp); err != nil {
  193. return nil, errors.Wrap(err, "unmarshal hailuo task data failed")
  194. }
  195. openAIVideo := originTask.ToOpenAIVideo()
  196. if hailuoResp.BaseResp.StatusCode != StatusSuccess {
  197. openAIVideo.Error = &dto.OpenAIVideoError{
  198. Message: hailuoResp.BaseResp.StatusMsg,
  199. Code: strconv.Itoa(hailuoResp.BaseResp.StatusCode),
  200. }
  201. }
  202. jsonData, err := common.Marshal(openAIVideo)
  203. if err != nil {
  204. return nil, errors.Wrap(err, "marshal openai video failed")
  205. }
  206. return jsonData, nil
  207. }
  208. func (a *TaskAdaptor) buildVideoURL(_, fileID string) string {
  209. if a.apiKey == "" || a.baseURL == "" {
  210. return ""
  211. }
  212. url := fmt.Sprintf("%s/v1/files/retrieve?file_id=%s", a.baseURL, fileID)
  213. req, err := http.NewRequest(http.MethodGet, url, nil)
  214. if err != nil {
  215. return ""
  216. }
  217. req.Header.Set("Accept", "application/json")
  218. req.Header.Set("Authorization", "Bearer "+a.apiKey)
  219. resp, err := service.GetHttpClient().Do(req)
  220. if err != nil {
  221. return ""
  222. }
  223. defer resp.Body.Close()
  224. responseBody, err := io.ReadAll(resp.Body)
  225. if err != nil {
  226. return ""
  227. }
  228. var retrieveResp RetrieveFileResponse
  229. if err := json.Unmarshal(responseBody, &retrieveResp); err != nil {
  230. return ""
  231. }
  232. if retrieveResp.BaseResp.StatusCode != StatusSuccess {
  233. return ""
  234. }
  235. return retrieveResp.File.DownloadURL
  236. }
  237. func contains(slice []string, item string) bool {
  238. for _, s := range slice {
  239. if s == item {
  240. return true
  241. }
  242. }
  243. return false
  244. }
  245. func containsInt(slice []int, item int) bool {
  246. for _, s := range slice {
  247. if s == item {
  248. return true
  249. }
  250. }
  251. return false
  252. }