image.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package minimax
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "github.com/QuantumNous/new-api/common"
  9. "github.com/QuantumNous/new-api/dto"
  10. relaycommon "github.com/QuantumNous/new-api/relay/common"
  11. "github.com/QuantumNous/new-api/service"
  12. "github.com/QuantumNous/new-api/types"
  13. "github.com/gin-gonic/gin"
  14. )
  15. type MiniMaxImageRequest struct {
  16. Model string `json:"model"`
  17. Prompt string `json:"prompt"`
  18. AspectRatio string `json:"aspect_ratio,omitempty"`
  19. ResponseFormat string `json:"response_format,omitempty"`
  20. N int `json:"n,omitempty"`
  21. PromptOptimizer *bool `json:"prompt_optimizer,omitempty"`
  22. AigcWatermark *bool `json:"aigc_watermark,omitempty"`
  23. }
  24. type MiniMaxImageResponse struct {
  25. ID string `json:"id"`
  26. Data struct {
  27. ImageURLs []string `json:"image_urls"`
  28. ImageBase64 []string `json:"image_base64"`
  29. } `json:"data"`
  30. Metadata map[string]any `json:"metadata"`
  31. BaseResp struct {
  32. StatusCode int `json:"status_code"`
  33. StatusMsg string `json:"status_msg"`
  34. } `json:"base_resp"`
  35. }
  36. func oaiImage2MiniMaxImageRequest(request dto.ImageRequest) MiniMaxImageRequest {
  37. responseFormat := normalizeMiniMaxResponseFormat(request.ResponseFormat)
  38. minimaxRequest := MiniMaxImageRequest{
  39. Model: request.Model,
  40. Prompt: request.Prompt,
  41. ResponseFormat: responseFormat,
  42. N: 1,
  43. AigcWatermark: request.Watermark,
  44. }
  45. if request.Model == "" {
  46. minimaxRequest.Model = "image-01"
  47. }
  48. if request.N != nil && *request.N > 0 {
  49. minimaxRequest.N = int(*request.N)
  50. }
  51. if aspectRatio := aspectRatioFromImageRequest(request); aspectRatio != "" {
  52. minimaxRequest.AspectRatio = aspectRatio
  53. }
  54. if raw, ok := request.Extra["prompt_optimizer"]; ok {
  55. var promptOptimizer bool
  56. if err := common.Unmarshal(raw, &promptOptimizer); err == nil {
  57. minimaxRequest.PromptOptimizer = &promptOptimizer
  58. }
  59. }
  60. return minimaxRequest
  61. }
  62. func aspectRatioFromImageRequest(request dto.ImageRequest) string {
  63. if raw, ok := request.Extra["aspect_ratio"]; ok {
  64. var aspectRatio string
  65. if err := common.Unmarshal(raw, &aspectRatio); err == nil && aspectRatio != "" {
  66. return aspectRatio
  67. }
  68. }
  69. switch request.Size {
  70. case "1024x1024":
  71. return "1:1"
  72. case "1792x1024":
  73. return "16:9"
  74. case "1024x1792":
  75. return "9:16"
  76. case "1536x1024", "1248x832":
  77. return "3:2"
  78. case "1024x1536", "832x1248":
  79. return "2:3"
  80. case "1152x864":
  81. return "4:3"
  82. case "864x1152":
  83. return "3:4"
  84. case "1344x576":
  85. return "21:9"
  86. }
  87. width, height, ok := parseImageSize(request.Size)
  88. if !ok {
  89. return ""
  90. }
  91. ratio := reduceAspectRatio(width, height)
  92. switch ratio {
  93. case "1:1", "16:9", "4:3", "3:2", "2:3", "3:4", "9:16", "21:9":
  94. return ratio
  95. default:
  96. return ""
  97. }
  98. }
  99. func parseImageSize(size string) (int, int, bool) {
  100. parts := strings.Split(size, "x")
  101. if len(parts) != 2 {
  102. return 0, 0, false
  103. }
  104. width, err := strconv.Atoi(parts[0])
  105. if err != nil {
  106. return 0, 0, false
  107. }
  108. height, err := strconv.Atoi(parts[1])
  109. if err != nil {
  110. return 0, 0, false
  111. }
  112. if width <= 0 || height <= 0 {
  113. return 0, 0, false
  114. }
  115. return width, height, true
  116. }
  117. func reduceAspectRatio(width, height int) string {
  118. divisor := gcd(width, height)
  119. return fmt.Sprintf("%d:%d", width/divisor, height/divisor)
  120. }
  121. func gcd(a, b int) int {
  122. for b != 0 {
  123. a, b = b, a%b
  124. }
  125. if a == 0 {
  126. return 1
  127. }
  128. return a
  129. }
  130. func normalizeMiniMaxResponseFormat(responseFormat string) string {
  131. switch strings.ToLower(responseFormat) {
  132. case "", "url":
  133. return "url"
  134. case "b64_json", "base64":
  135. return "base64"
  136. default:
  137. return responseFormat
  138. }
  139. }
  140. func responseMiniMax2OpenAIImage(response *MiniMaxImageResponse, info *relaycommon.RelayInfo) (*dto.ImageResponse, error) {
  141. imageResponse := &dto.ImageResponse{
  142. Created: info.StartTime.Unix(),
  143. }
  144. for _, imageURL := range response.Data.ImageURLs {
  145. imageResponse.Data = append(imageResponse.Data, dto.ImageData{Url: imageURL})
  146. }
  147. for _, imageBase64 := range response.Data.ImageBase64 {
  148. imageResponse.Data = append(imageResponse.Data, dto.ImageData{B64Json: imageBase64})
  149. }
  150. if len(response.Metadata) > 0 {
  151. metadata, err := common.Marshal(response.Metadata)
  152. if err != nil {
  153. return nil, err
  154. }
  155. imageResponse.Metadata = metadata
  156. }
  157. return imageResponse, nil
  158. }
  159. func miniMaxImageHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (*dto.Usage, *types.NewAPIError) {
  160. responseBody, err := io.ReadAll(resp.Body)
  161. if err != nil {
  162. return nil, types.NewOpenAIError(err, types.ErrorCodeReadResponseBodyFailed, http.StatusInternalServerError)
  163. }
  164. service.CloseResponseBodyGracefully(resp)
  165. var minimaxResponse MiniMaxImageResponse
  166. if err := common.Unmarshal(responseBody, &minimaxResponse); err != nil {
  167. return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  168. }
  169. if minimaxResponse.BaseResp.StatusCode != 0 {
  170. return nil, types.WithOpenAIError(types.OpenAIError{
  171. Message: minimaxResponse.BaseResp.StatusMsg,
  172. Type: "minimax_image_error",
  173. Code: fmt.Sprintf("%d", minimaxResponse.BaseResp.StatusCode),
  174. }, resp.StatusCode)
  175. }
  176. openAIResponse, err := responseMiniMax2OpenAIImage(&minimaxResponse, info)
  177. if err != nil {
  178. return nil, types.NewError(err, types.ErrorCodeBadResponseBody)
  179. }
  180. jsonResponse, err := common.Marshal(openAIResponse)
  181. if err != nil {
  182. return nil, types.NewError(err, types.ErrorCodeBadResponseBody)
  183. }
  184. c.Writer.Header().Set("Content-Type", "application/json")
  185. c.Writer.WriteHeader(resp.StatusCode)
  186. if _, err := c.Writer.Write(jsonResponse); err != nil {
  187. return nil, types.NewError(err, types.ErrorCodeBadResponseBody)
  188. }
  189. return &dto.Usage{}, nil
  190. }