-
Notifications
You must be signed in to change notification settings - Fork 0
/
upscale_conservative.go
88 lines (74 loc) · 2.41 KB
/
upscale_conservative.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package stabilityai
import (
"bytes"
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
)
type UpscaleConservativeRequest struct {
Image io.Reader
Prompt string
NegativePrompt string
Seed int
Output Output
Creativity float64
}
func (c *Client) UpscaleConservative(ctx context.Context, req UpscaleConservativeRequest, out io.Writer) error {
buff := bytes.Buffer{}
form := multipart.NewWriter(&buff)
img, err := form.CreateFormFile("image", "image")
if err != nil {
return fmt.Errorf("failed to create form field image: %w", err)
}
if _, err := io.Copy(img, req.Image); err != nil {
return fmt.Errorf("failed to copy image to form field: %w", err)
}
if err := form.WriteField("prompt", req.Prompt); err != nil {
return fmt.Errorf("failed to write field prompt: %w", err)
}
if req.NegativePrompt != "" {
if err := form.WriteField("negative_prompt", req.NegativePrompt); err != nil {
return fmt.Errorf("failed to write field negative_prompt: %w", err)
}
}
if req.Seed > 0 {
if err := form.WriteField("seed", fmt.Sprintf("%d", req.Seed)); err != nil {
return fmt.Errorf("failed to write field seed: %w", err)
}
}
if req.Output != "" {
if err := form.WriteField("output_format", string(req.Output)); err != nil {
return fmt.Errorf("failed to write field output_format: %w", err)
}
}
if req.Creativity > 0 {
if err := form.WriteField("creativity", fmt.Sprintf("%f", req.Creativity)); err != nil {
return fmt.Errorf("failed to write field creativity: %w", err)
}
}
if err := form.Close(); err != nil {
return fmt.Errorf("failed to close multipart writer: %w", err)
}
url := "https://api.stability.ai/v2beta/stable-image/upscale/conservative"
rq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, &buff)
if err != nil {
return fmt.Errorf("failed to create request %s: %w", url, err)
}
rq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.apiKey))
rq.Header.Set("Content-Type", form.FormDataContentType())
rq.Header.Set("Accept", "image/*")
resp, err := c.httpClient.Do(rq)
if err != nil {
return fmt.Errorf("failed to send request %s: %w", url, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code %s: %d", url, resp.StatusCode)
}
if _, err := io.Copy(out, resp.Body); err != nil {
return fmt.Errorf("failed to copy response body %s: %w", url, err)
}
return nil
}