2
0

adaptor.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. package ali
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/dto"
  11. "github.com/QuantumNous/new-api/logger"
  12. "github.com/QuantumNous/new-api/model"
  13. "github.com/QuantumNous/new-api/relay/channel"
  14. relaycommon "github.com/QuantumNous/new-api/relay/common"
  15. "github.com/QuantumNous/new-api/service"
  16. "github.com/samber/lo"
  17. "github.com/gin-gonic/gin"
  18. "github.com/pkg/errors"
  19. )
  20. // ============================
  21. // Request / Response structures
  22. // ============================
  23. // AliVideoRequest 阿里通义万相视频生成请求
  24. type AliVideoRequest struct {
  25. Model string `json:"model"`
  26. Input AliVideoInput `json:"input"`
  27. Parameters *AliVideoParameters `json:"parameters,omitempty"`
  28. }
  29. // AliVideoInput 视频输入参数
  30. type AliVideoInput struct {
  31. Prompt string `json:"prompt,omitempty"` // 文本提示词
  32. ImgURL string `json:"img_url,omitempty"` // 首帧图像URL或Base64(图生视频)
  33. FirstFrameURL string `json:"first_frame_url,omitempty"` // 首帧图片URL(首尾帧生视频)
  34. LastFrameURL string `json:"last_frame_url,omitempty"` // 尾帧图片URL(首尾帧生视频)
  35. AudioURL string `json:"audio_url,omitempty"` // 音频URL(wan2.5支持)
  36. NegativePrompt string `json:"negative_prompt,omitempty"` // 反向提示词
  37. Template string `json:"template,omitempty"` // 视频特效模板
  38. }
  39. // AliVideoParameters 视频参数
  40. type AliVideoParameters struct {
  41. Resolution string `json:"resolution,omitempty"` // 分辨率: 480P/720P/1080P(图生视频、首尾帧生视频)
  42. Size string `json:"size,omitempty"` // 尺寸: 如 "832*480"(文生视频)
  43. Duration int `json:"duration,omitempty"` // 时长: 3-10秒
  44. PromptExtend bool `json:"prompt_extend,omitempty"` // 是否开启prompt智能改写
  45. Watermark bool `json:"watermark,omitempty"` // 是否添加水印
  46. Audio *bool `json:"audio,omitempty"` // 是否添加音频(wan2.5)
  47. Seed int `json:"seed,omitempty"` // 随机数种子
  48. }
  49. // AliVideoResponse 阿里通义万相响应
  50. type AliVideoResponse struct {
  51. Output AliVideoOutput `json:"output"`
  52. RequestID string `json:"request_id"`
  53. Code string `json:"code,omitempty"`
  54. Message string `json:"message,omitempty"`
  55. Usage *AliUsage `json:"usage,omitempty"`
  56. }
  57. // AliVideoOutput 输出信息
  58. type AliVideoOutput struct {
  59. TaskID string `json:"task_id"`
  60. TaskStatus string `json:"task_status"`
  61. SubmitTime string `json:"submit_time,omitempty"`
  62. ScheduledTime string `json:"scheduled_time,omitempty"`
  63. EndTime string `json:"end_time,omitempty"`
  64. OrigPrompt string `json:"orig_prompt,omitempty"`
  65. ActualPrompt string `json:"actual_prompt,omitempty"`
  66. VideoURL string `json:"video_url,omitempty"`
  67. Code string `json:"code,omitempty"`
  68. Message string `json:"message,omitempty"`
  69. }
  70. // AliUsage 使用统计
  71. type AliUsage struct {
  72. Duration int `json:"duration,omitempty"`
  73. VideoCount int `json:"video_count,omitempty"`
  74. SR int `json:"SR,omitempty"`
  75. }
  76. type AliMetadata struct {
  77. // Input 相关
  78. AudioURL string `json:"audio_url,omitempty"` // 音频URL
  79. ImgURL string `json:"img_url,omitempty"` // 图片URL(图生视频)
  80. FirstFrameURL string `json:"first_frame_url,omitempty"` // 首帧图片URL(首尾帧生视频)
  81. LastFrameURL string `json:"last_frame_url,omitempty"` // 尾帧图片URL(首尾帧生视频)
  82. NegativePrompt string `json:"negative_prompt,omitempty"` // 反向提示词
  83. Template string `json:"template,omitempty"` // 视频特效模板
  84. // Parameters 相关
  85. Resolution *string `json:"resolution,omitempty"` // 分辨率: 480P/720P/1080P
  86. Size *string `json:"size,omitempty"` // 尺寸: 如 "832*480"
  87. Duration *int `json:"duration,omitempty"` // 时长
  88. PromptExtend *bool `json:"prompt_extend,omitempty"` // 是否开启prompt智能改写
  89. Watermark *bool `json:"watermark,omitempty"` // 是否添加水印
  90. Audio *bool `json:"audio,omitempty"` // 是否添加音频
  91. Seed *int `json:"seed,omitempty"` // 随机数种子
  92. }
  93. // ============================
  94. // Adaptor implementation
  95. // ============================
  96. type TaskAdaptor struct {
  97. ChannelType int
  98. apiKey string
  99. baseURL string
  100. aliReq *AliVideoRequest
  101. }
  102. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  103. a.ChannelType = info.ChannelType
  104. a.baseURL = info.ChannelBaseUrl
  105. a.apiKey = info.ApiKey
  106. }
  107. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  108. // 阿里通义万相支持 JSON 格式,不使用 multipart
  109. var taskReq relaycommon.TaskSubmitReq
  110. if err := common.UnmarshalBodyReusable(c, &taskReq); err != nil {
  111. return service.TaskErrorWrapper(err, "unmarshal_task_request_failed", http.StatusBadRequest)
  112. }
  113. aliReq, err := a.convertToAliRequest(info, taskReq)
  114. if err != nil {
  115. return service.TaskErrorWrapper(err, "convert_to_ali_request_failed", http.StatusInternalServerError)
  116. }
  117. a.aliReq = aliReq
  118. logger.LogJson(c, "ali video request body", aliReq)
  119. return relaycommon.ValidateMultipartDirect(c, info)
  120. }
  121. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  122. return fmt.Sprintf("%s/api/v1/services/aigc/video-generation/video-synthesis", a.baseURL), nil
  123. }
  124. // BuildRequestHeader sets required headers for Ali API
  125. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  126. req.Header.Set("Authorization", "Bearer "+a.apiKey)
  127. req.Header.Set("Content-Type", "application/json")
  128. req.Header.Set("X-DashScope-Async", "enable") // 阿里异步任务必须设置
  129. return nil
  130. }
  131. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  132. bodyBytes, err := common.Marshal(a.aliReq)
  133. if err != nil {
  134. return nil, errors.Wrap(err, "marshal_ali_request_failed")
  135. }
  136. return bytes.NewReader(bodyBytes), nil
  137. }
  138. var (
  139. size480p = []string{
  140. "832*480",
  141. "480*832",
  142. "624*624",
  143. }
  144. size720p = []string{
  145. "1280*720",
  146. "720*1280",
  147. "960*960",
  148. "1088*832",
  149. "832*1088",
  150. }
  151. size1080p = []string{
  152. "1920*1080",
  153. "1080*1920",
  154. "1440*1440",
  155. "1632*1248",
  156. "1248*1632",
  157. }
  158. )
  159. func sizeToResolution(size string) (string, error) {
  160. if lo.Contains(size480p, size) {
  161. return "480P", nil
  162. } else if lo.Contains(size720p, size) {
  163. return "720P", nil
  164. } else if lo.Contains(size1080p, size) {
  165. return "1080P", nil
  166. }
  167. return "", fmt.Errorf("invalid size: %s", size)
  168. }
  169. func ProcessAliOtherRatios(aliReq *AliVideoRequest) (map[string]float64, error) {
  170. otherRatios := make(map[string]float64)
  171. aliRatios := map[string]map[string]float64{
  172. "wan2.5-t2v-preview": {
  173. "480P": 1,
  174. "720P": 2,
  175. "1080P": 1 / 0.3,
  176. },
  177. "wan2.2-t2v-plus": {
  178. "480P": 1,
  179. "1080P": 0.7 / 0.14,
  180. },
  181. "wan2.5-i2v-preview": {
  182. "480P": 1,
  183. "720P": 2,
  184. "1080P": 1 / 0.3,
  185. },
  186. "wan2.2-i2v-plus": {
  187. "480P": 1,
  188. "1080P": 0.7 / 0.14,
  189. },
  190. "wan2.2-kf2v-flash": {
  191. "480P": 1,
  192. "720P": 2,
  193. "1080P": 4.8,
  194. },
  195. "wan2.2-i2v-flash": {
  196. "480P": 1,
  197. "720P": 2,
  198. },
  199. "wan2.2-s2v": {
  200. "480P": 1,
  201. "720P": 0.9 / 0.5,
  202. },
  203. }
  204. var resolution string
  205. // size match
  206. if aliReq.Parameters.Size != "" {
  207. toResolution, err := sizeToResolution(aliReq.Parameters.Size)
  208. if err != nil {
  209. return nil, err
  210. }
  211. resolution = toResolution
  212. } else {
  213. resolution = strings.ToUpper(aliReq.Parameters.Resolution)
  214. if !strings.HasSuffix(resolution, "P") {
  215. resolution = resolution + "P"
  216. }
  217. }
  218. if otherRatio, ok := aliRatios[aliReq.Model]; ok {
  219. if ratio, ok := otherRatio[resolution]; ok {
  220. otherRatios[fmt.Sprintf("resolution-%s", resolution)] = ratio
  221. }
  222. }
  223. return otherRatios, nil
  224. }
  225. func (a *TaskAdaptor) convertToAliRequest(info *relaycommon.RelayInfo, req relaycommon.TaskSubmitReq) (*AliVideoRequest, error) {
  226. aliReq := &AliVideoRequest{
  227. Model: req.Model,
  228. Input: AliVideoInput{
  229. Prompt: req.Prompt,
  230. ImgURL: req.InputReference,
  231. },
  232. Parameters: &AliVideoParameters{
  233. PromptExtend: true, // 默认开启智能改写
  234. Watermark: false,
  235. },
  236. }
  237. // 处理分辨率映射
  238. if req.Size != "" {
  239. // text to video size must be contained *
  240. if strings.Contains(req.Model, "t2v") && !strings.Contains(req.Size, "*") {
  241. return nil, fmt.Errorf("invalid size: %s, example: %s", req.Size, "1920*1080")
  242. }
  243. if strings.Contains(req.Size, "*") {
  244. aliReq.Parameters.Size = req.Size
  245. } else {
  246. resolution := strings.ToUpper(req.Size)
  247. // 支持 480p, 720p, 1080p 或 480P, 720P, 1080P
  248. if !strings.HasSuffix(resolution, "P") {
  249. resolution = resolution + "P"
  250. }
  251. aliReq.Parameters.Resolution = resolution
  252. }
  253. } else {
  254. // 根据模型设置默认分辨率
  255. if strings.Contains(req.Model, "t2v") { // image to video
  256. if strings.HasPrefix(req.Model, "wan2.5") {
  257. aliReq.Parameters.Size = "1920*1080"
  258. } else if strings.HasPrefix(req.Model, "wan2.2") {
  259. aliReq.Parameters.Size = "1920*1080"
  260. } else {
  261. aliReq.Parameters.Size = "1280*720"
  262. }
  263. } else {
  264. if strings.HasPrefix(req.Model, "wan2.5") {
  265. aliReq.Parameters.Resolution = "1080P"
  266. } else if strings.HasPrefix(req.Model, "wan2.2-i2v-flash") {
  267. aliReq.Parameters.Resolution = "720P"
  268. } else if strings.HasPrefix(req.Model, "wan2.2-i2v-plus") {
  269. aliReq.Parameters.Resolution = "1080P"
  270. } else {
  271. aliReq.Parameters.Resolution = "720P"
  272. }
  273. }
  274. }
  275. // 处理时长
  276. if req.Duration > 0 {
  277. aliReq.Parameters.Duration = req.Duration
  278. } else if req.Seconds != "" {
  279. seconds, err := strconv.Atoi(req.Seconds)
  280. if err != nil {
  281. return nil, errors.Wrap(err, "convert seconds to int failed")
  282. } else {
  283. aliReq.Parameters.Duration = seconds
  284. }
  285. } else {
  286. aliReq.Parameters.Duration = 5 // 默认5秒
  287. }
  288. // 从 metadata 中提取额外参数
  289. if req.Metadata != nil {
  290. if metadataBytes, err := common.Marshal(req.Metadata); err == nil {
  291. err = common.Unmarshal(metadataBytes, aliReq)
  292. if err != nil {
  293. return nil, errors.Wrap(err, "unmarshal metadata failed")
  294. }
  295. } else {
  296. return nil, errors.Wrap(err, "marshal metadata failed")
  297. }
  298. }
  299. if aliReq.Model != req.Model {
  300. return nil, errors.New("can't change model with metadata")
  301. }
  302. info.PriceData.OtherRatios = map[string]float64{
  303. "seconds": float64(aliReq.Parameters.Duration),
  304. }
  305. ratios, err := ProcessAliOtherRatios(aliReq)
  306. if err != nil {
  307. return nil, err
  308. }
  309. for s, f := range ratios {
  310. info.PriceData.OtherRatios[s] = f
  311. }
  312. return aliReq, nil
  313. }
  314. // DoRequest delegates to common helper
  315. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  316. return channel.DoTaskApiRequest(a, c, info, requestBody)
  317. }
  318. // DoResponse handles upstream response
  319. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  320. responseBody, err := io.ReadAll(resp.Body)
  321. if err != nil {
  322. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  323. return
  324. }
  325. _ = resp.Body.Close()
  326. // 解析阿里响应
  327. var aliResp AliVideoResponse
  328. if err := common.Unmarshal(responseBody, &aliResp); err != nil {
  329. taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
  330. return
  331. }
  332. // 检查错误
  333. if aliResp.Code != "" {
  334. taskErr = service.TaskErrorWrapper(fmt.Errorf("%s: %s", aliResp.Code, aliResp.Message), "ali_api_error", resp.StatusCode)
  335. return
  336. }
  337. if aliResp.Output.TaskID == "" {
  338. taskErr = service.TaskErrorWrapper(fmt.Errorf("task_id is empty"), "invalid_response", http.StatusInternalServerError)
  339. return
  340. }
  341. // 转换为 OpenAI 格式响应
  342. openAIResp := dto.NewOpenAIVideo()
  343. openAIResp.ID = aliResp.Output.TaskID
  344. openAIResp.Model = c.GetString("model")
  345. if openAIResp.Model == "" && info != nil {
  346. openAIResp.Model = info.OriginModelName
  347. }
  348. openAIResp.Status = convertAliStatus(aliResp.Output.TaskStatus)
  349. openAIResp.CreatedAt = common.GetTimestamp()
  350. // 返回 OpenAI 格式
  351. c.JSON(http.StatusOK, openAIResp)
  352. return aliResp.Output.TaskID, responseBody, nil
  353. }
  354. // FetchTask 查询任务状态
  355. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any) (*http.Response, error) {
  356. taskID, ok := body["task_id"].(string)
  357. if !ok {
  358. return nil, fmt.Errorf("invalid task_id")
  359. }
  360. uri := fmt.Sprintf("%s/api/v1/tasks/%s", baseUrl, taskID)
  361. req, err := http.NewRequest(http.MethodGet, uri, nil)
  362. if err != nil {
  363. return nil, err
  364. }
  365. req.Header.Set("Authorization", "Bearer "+key)
  366. return service.GetHttpClient().Do(req)
  367. }
  368. func (a *TaskAdaptor) GetModelList() []string {
  369. return ModelList
  370. }
  371. func (a *TaskAdaptor) GetChannelName() string {
  372. return ChannelName
  373. }
  374. // ParseTaskResult 解析任务结果
  375. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  376. var aliResp AliVideoResponse
  377. if err := common.Unmarshal(respBody, &aliResp); err != nil {
  378. return nil, errors.Wrap(err, "unmarshal task result failed")
  379. }
  380. taskResult := relaycommon.TaskInfo{
  381. Code: 0,
  382. }
  383. // 状态映射
  384. switch aliResp.Output.TaskStatus {
  385. case "PENDING":
  386. taskResult.Status = model.TaskStatusQueued
  387. case "RUNNING":
  388. taskResult.Status = model.TaskStatusInProgress
  389. case "SUCCEEDED":
  390. taskResult.Status = model.TaskStatusSuccess
  391. // 阿里直接返回视频URL,不需要额外的代理端点
  392. taskResult.Url = aliResp.Output.VideoURL
  393. case "FAILED", "CANCELED", "UNKNOWN":
  394. taskResult.Status = model.TaskStatusFailure
  395. if aliResp.Message != "" {
  396. taskResult.Reason = aliResp.Message
  397. } else if aliResp.Output.Message != "" {
  398. taskResult.Reason = fmt.Sprintf("task failed, code: %s , message: %s", aliResp.Output.Code, aliResp.Output.Message)
  399. } else {
  400. taskResult.Reason = "task failed"
  401. }
  402. default:
  403. taskResult.Status = model.TaskStatusQueued
  404. }
  405. return &taskResult, nil
  406. }
  407. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  408. var aliResp AliVideoResponse
  409. if err := common.Unmarshal(task.Data, &aliResp); err != nil {
  410. return nil, errors.Wrap(err, "unmarshal ali response failed")
  411. }
  412. openAIResp := dto.NewOpenAIVideo()
  413. openAIResp.ID = task.TaskID
  414. openAIResp.Status = convertAliStatus(aliResp.Output.TaskStatus)
  415. openAIResp.Model = task.Properties.OriginModelName
  416. openAIResp.SetProgressStr(task.Progress)
  417. openAIResp.CreatedAt = task.CreatedAt
  418. openAIResp.CompletedAt = task.UpdatedAt
  419. // 设置视频URL(核心字段)
  420. openAIResp.SetMetadata("url", aliResp.Output.VideoURL)
  421. // 错误处理
  422. if aliResp.Code != "" {
  423. openAIResp.Error = &dto.OpenAIVideoError{
  424. Code: aliResp.Code,
  425. Message: aliResp.Message,
  426. }
  427. } else if aliResp.Output.Code != "" {
  428. openAIResp.Error = &dto.OpenAIVideoError{
  429. Code: aliResp.Output.Code,
  430. Message: aliResp.Output.Message,
  431. }
  432. }
  433. return common.Marshal(openAIResp)
  434. }
  435. func convertAliStatus(aliStatus string) string {
  436. switch aliStatus {
  437. case "PENDING":
  438. return dto.VideoStatusQueued
  439. case "RUNNING":
  440. return dto.VideoStatusInProgress
  441. case "SUCCEEDED":
  442. return dto.VideoStatusCompleted
  443. case "FAILED", "CANCELED", "UNKNOWN":
  444. return dto.VideoStatusFailed
  445. default:
  446. return dto.VideoStatusUnknown
  447. }
  448. }