|
| 1 | +package handler |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/base64" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "log/slog" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + "strconv" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/gin-gonic/gin" |
| 15 | + "github.com/openai/openai-go" |
| 16 | + |
| 17 | + "github.com/NexaAI/nexa-sdk/runner/internal/types" |
| 18 | + nexa_sdk "github.com/NexaAI/nexa-sdk/runner/nexa-sdk" |
| 19 | + "github.com/NexaAI/nexa-sdk/runner/server/service" |
| 20 | +) |
| 21 | + |
| 22 | +// @Router /images/generations [post] |
| 23 | +// @Summary Creates an image given a prompt. |
| 24 | +// @Description Creates an image given a prompt. This endpoint follows OpenAI DALL-E 3 API specification for compatibility. |
| 25 | +// @Accept json |
| 26 | +// @Param request body openai.ImageGenerateParams true "Image generation request" |
| 27 | +// @Produce json |
| 28 | +// @Success 200 {object} openai.ImagesResponse "Successful image generation response" |
| 29 | +// @Failure 400 {object} map[string]any "Bad request - invalid parameters" |
| 30 | +// @Failure 404 {object} map[string]any "Model not found" |
| 31 | +// @Failure 500 {object} map[string]any "Internal server error" |
| 32 | +func ImageGenerations(c *gin.Context) { |
| 33 | + param := openai.ImageGenerateParams{} |
| 34 | + if err := c.ShouldBindJSON(¶m); err != nil { |
| 35 | + slog.Error("Failed to bind JSON request", "error", err) |
| 36 | + c.JSON(http.StatusBadRequest, map[string]any{"error": err.Error()}) |
| 37 | + return |
| 38 | + } |
| 39 | + |
| 40 | + slog.Info("Image generation request received", |
| 41 | + "model", param.Model, |
| 42 | + "prompt_length", len(param.Prompt), |
| 43 | + "n", param.N, |
| 44 | + "size", param.Size) |
| 45 | + |
| 46 | + if param.N.Value == 0 { |
| 47 | + param.N.Value = 1 |
| 48 | + } |
| 49 | + if param.Size == "" { |
| 50 | + param.Size = openai.ImageGenerateParamsSize256x256 |
| 51 | + } |
| 52 | + if param.ResponseFormat == "" { |
| 53 | + param.ResponseFormat = openai.ImageGenerateParamsResponseFormatURL |
| 54 | + } |
| 55 | + |
| 56 | + imageGen, err := service.KeepAliveGet[nexa_sdk.ImageGen]( |
| 57 | + param.Model, |
| 58 | + types.ModelParam{}, |
| 59 | + c.GetHeader("Nexa-KeepCache") != "true", |
| 60 | + ) |
| 61 | + if err != nil { |
| 62 | + c.JSON(http.StatusInternalServerError, map[string]any{"error": err.Error()}) |
| 63 | + return |
| 64 | + } |
| 65 | + |
| 66 | + width, height, err := parseImageSize(string(param.Size)) |
| 67 | + if err != nil { |
| 68 | + c.JSON(http.StatusBadRequest, map[string]any{"error": err.Error()}) |
| 69 | + return |
| 70 | + } |
| 71 | + |
| 72 | + var imageData []openai.Image |
| 73 | + n := int(param.N.Value) |
| 74 | + slog.Info("Starting image generation", "count", n, "size", string(param.Size)) |
| 75 | + for i := range n { |
| 76 | + outputPath := fmt.Sprintf("imagegen_output_%d.png", time.Now().UnixNano()) |
| 77 | + slog.Debug("Generating image", "index", i, "output_path", outputPath) |
| 78 | + |
| 79 | + config := &nexa_sdk.ImageGenerationConfig{ |
| 80 | + Prompts: []string{param.Prompt}, |
| 81 | + NegativePrompts: []string{"blurry, low quality, distorted, low resolution"}, |
| 82 | + Height: height, |
| 83 | + Width: width, |
| 84 | + SamplerConfig: nexa_sdk.ImageSamplerConfig{ |
| 85 | + Method: "ddim", |
| 86 | + Steps: 20, |
| 87 | + GuidanceScale: 7.5, |
| 88 | + Eta: 0.0, |
| 89 | + Seed: int32(time.Now().UnixNano() % 1000000), |
| 90 | + }, |
| 91 | + SchedulerConfig: nexa_sdk.SchedulerConfig{ |
| 92 | + Type: "ddim", |
| 93 | + NumTrainTimesteps: 1000, |
| 94 | + StepsOffset: 1, |
| 95 | + BetaStart: 0.00085, |
| 96 | + BetaEnd: 0.012, |
| 97 | + BetaSchedule: "scaled_linear", |
| 98 | + PredictionType: "epsilon", |
| 99 | + TimestepType: "discrete", |
| 100 | + TimestepSpacing: "leading", |
| 101 | + InterpolationType: "linear", |
| 102 | + ConfigPath: "", |
| 103 | + }, |
| 104 | + Strength: 1.0, |
| 105 | + } |
| 106 | + |
| 107 | + result, err := imageGen.Txt2Img(nexa_sdk.ImageGenTxt2ImgInput{ |
| 108 | + PromptUTF8: param.Prompt, |
| 109 | + Config: config, |
| 110 | + OutputPath: outputPath, |
| 111 | + }) |
| 112 | + if err != nil { |
| 113 | + c.JSON(http.StatusInternalServerError, map[string]any{"error": fmt.Sprintf("image generation failed: %v", err)}) |
| 114 | + return |
| 115 | + } |
| 116 | + |
| 117 | + data := openai.Image{ |
| 118 | + RevisedPrompt: param.Prompt, |
| 119 | + } |
| 120 | + |
| 121 | + if param.ResponseFormat == openai.ImageGenerateParamsResponseFormatB64JSON { |
| 122 | + b64Data, err := encodeImageToBase64(result.OutputImagePath) |
| 123 | + os.Remove(result.OutputImagePath) |
| 124 | + if err != nil { |
| 125 | + c.JSON(http.StatusInternalServerError, map[string]any{"error": fmt.Sprintf("failed to encode image: %v", err)}) |
| 126 | + return |
| 127 | + } |
| 128 | + data.B64JSON = b64Data |
| 129 | + } else { |
| 130 | + data.URL = result.OutputImagePath |
| 131 | + } |
| 132 | + |
| 133 | + imageData = append(imageData, data) |
| 134 | + slog.Info("Image generated successfully", "index", i, "output_path", result.OutputImagePath) |
| 135 | + } |
| 136 | + |
| 137 | + response := openai.ImagesResponse{ |
| 138 | + Created: time.Now().Unix(), |
| 139 | + Data: imageData, |
| 140 | + } |
| 141 | + |
| 142 | + slog.Info("Image generation completed successfully", "total_images", len(imageData)) |
| 143 | + c.JSON(http.StatusOK, response) |
| 144 | +} |
| 145 | + |
| 146 | +func parseImageSize(size string) (int32, int32, error) { |
| 147 | + parts := strings.Split(size, "x") |
| 148 | + if len(parts) != 2 { |
| 149 | + return 0, 0, errors.New("invalid size format") |
| 150 | + } |
| 151 | + |
| 152 | + width, err := strconv.Atoi(parts[0]) |
| 153 | + if err != nil { |
| 154 | + return 0, 0, errors.New("invalid width") |
| 155 | + } |
| 156 | + |
| 157 | + height, err := strconv.Atoi(parts[1]) |
| 158 | + if err != nil { |
| 159 | + return 0, 0, errors.New("invalid height") |
| 160 | + } |
| 161 | + |
| 162 | + return int32(width), int32(height), nil |
| 163 | +} |
| 164 | + |
| 165 | +func encodeImageToBase64(imagePath string) (string, error) { |
| 166 | + imageData, err := os.ReadFile(imagePath) |
| 167 | + if err != nil { |
| 168 | + return "", fmt.Errorf("failed to read image file: %v", err) |
| 169 | + } |
| 170 | + mimeType := http.DetectContentType(imageData) |
| 171 | + base64String := base64.StdEncoding.EncodeToString(imageData) |
| 172 | + return fmt.Sprintf("data:%s;base64,%s", mimeType, base64String), nil |
| 173 | +} |
0 commit comments