-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
90 lines (76 loc) · 1.6 KB
/
main.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
89
90
package main
import (
"bufio"
"fmt"
"image"
"image/jpeg"
"image/png"
"mime"
"os"
"time"
"github.com/Kardbord/hfapigo/v3"
)
const HuggingFaceTokenEnv = "HUGGING_FACE_TOKEN"
func init() {
key := os.Getenv(HuggingFaceTokenEnv)
if key != "" {
hfapigo.SetAPIKey(key)
}
}
func main() {
fmt.Print("Enter an image prompt: ")
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
fmt.Print(err)
return
}
type ChanRv struct {
resp image.Image
format string
err error
}
ch := make(chan ChanRv)
fmt.Print("Sending request")
go func() {
img, fmt, err := hfapigo.SendTextToImageRequest(hfapigo.RecommendedTextToImageModel, &hfapigo.TextToImageRequest{
Inputs: input,
Options: *hfapigo.NewOptions().SetWaitForModel(true),
})
ch <- ChanRv{img, fmt, err}
}()
for {
select {
default:
fmt.Print(".")
time.Sleep(time.Millisecond * 300)
case chrv := <-ch:
if chrv.err != nil {
fmt.Printf("\nError from Hugging Face: %s\n", chrv.err)
return
}
filename := fmt.Sprintf("output.%s", chrv.format)
fout, err := os.Create(filename)
if err != nil {
fmt.Println(err)
return
}
defer fout.Close()
mimetype := mime.TypeByExtension(fmt.Sprintf(".%s", chrv.format))
switch mimetype {
case "image/jpeg":
err = jpeg.Encode(fout, chrv.resp, nil)
case "image/png":
err = png.Encode(fout, chrv.resp)
default:
err = fmt.Errorf("unknown image format: %s", chrv.format)
}
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("\nWrote image to %s\n", filename)
}
return
}
}
}