-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
195 lines (164 loc) · 4.73 KB
/
main.go
File metadata and controls
195 lines (164 loc) · 4.73 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package main
import (
"bytes"
"encoding/json"
"fmt"
"image/color"
"io"
"log"
"net/http"
"os"
"regexp"
"strings"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/canvas"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/widget"
"github.com/joho/godotenv"
)
type PixelData struct {
Data [][]int `json:"data"`
}
var (
apiKey = " "
apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key="
)
var generateButton *widget.Button
func fetchPixelData(prompt string) (*PixelData, error) {
if prompt == "" {
return nil, fmt.Errorf("input cannot be empty")
}
systemInstruction := `Generate a JSON response containing a **high-detail 2D boolean matrix representation** of an object based on the given input: "{object_name}".
### **Output Format (ALWAYS JSON)**:
{
"data": [
[0, 0, 1, 1, 1, 0, 0, 0, 1, 1],
[0, 1, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 0, 0]
]
}
### Rules:
- Always return output as a valid JSON object.
- The "data" field must contain a nested list of integers (0 or 1) with a grid size between 10x10 and 20x20.
- Ensure that the pixel representation closely matches the given "{object_name}".
- Do not add any explanation outside of the JSON response.
Now, generate the binary matrix for: **"{object_name}"**`
requestData := map[string]any{
"contents": []map[string]any{
{"role": "user", "parts": []map[string]string{{"text": prompt}}},
},
"systemInstruction": map[string]any{
"role": "system",
"parts": []map[string]string{{"text": systemInstruction}},
},
}
requestBody, err := json.Marshal(requestData)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", apiUrl+apiKey, bytes.NewBuffer(requestBody))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(req)
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
var apiResponse map[string]any
if err := json.Unmarshal(body, &apiResponse); err != nil {
return nil, err
}
candidates, ok := apiResponse["candidates"].([]any)
if !ok || len(candidates) == 0 {
return nil, fmt.Errorf("invalid response format")
}
content, ok := candidates[0].(map[string]any)["content"].(map[string]any)
if !ok {
return nil, fmt.Errorf("missing content field")
}
parts, ok := content["parts"].([]any)
if !ok || len(parts) == 0 {
return nil, fmt.Errorf("invalid parts data")
}
responseText, _ := parts[0].(map[string]any)["text"].(string)
cleanedText := strings.TrimSpace(responseText)
regex := regexp.MustCompile("^```json\\n|```$")
cleanedText = regex.ReplaceAllString(cleanedText, "")
// log.Println("Cleaned Text:", cleanedText)
var pixelData PixelData
if err := json.Unmarshal([]byte(cleanedText), &pixelData); err != nil {
return nil, err
}
return &pixelData, nil
}
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
apiKey = os.Getenv("API_KEY")
application := app.New()
window := application.NewWindow("AI BIT Map Gen")
window.Resize(fyne.NewSize(500, 600))
message := widget.NewLabel("This AI can draw 2D art shapes")
inputPrompt := widget.NewEntry()
inputPrompt.SetPlaceHolder("Enter object name...")
gridContainer := container.NewWithoutLayout()
generateButton = widget.NewButton("Generate", func() {
message.SetText("Generating image...")
gridContainer.Objects = nil
gridContainer.Refresh()
pixelData, err := fetchPixelData(inputPrompt.Text)
if err != nil {
log.Println("Error:", err)
message.SetText("Failed to generate image. Try again.")
return
}
message.SetText("Image generated successfully!")
inputPrompt.SetText("")
var tiles []fyne.CanvasObject
tileSize := 20
offsetX := 10
offsetY := 10
for rowIdx, row := range pixelData.Data {
for colIdx, col := range row {
if col == 1 {
x := offsetX + (colIdx * tileSize)
y := offsetY + (rowIdx * tileSize)
rect := rectDraw(x, y)
rect.FillColor = color.NRGBA{R: 0xff, G: 0x33, B: 0x33, A: 0xff}
tiles = append(tiles, rect)
}
}
}
gridContainer.Objects = tiles
gridContainer.Refresh()
})
window.SetContent(container.NewVBox(
message,
inputPrompt,
generateButton,
gridContainer,
))
window.ShowAndRun()
}
func rectDraw(x int, y int) *canvas.Rectangle {
blue := color.NRGBA{R: 0, G: 0, B: 180, A: 255}
rect := canvas.NewRectangle(blue)
rect.Move(fyne.NewPos(float32(x), float32(y)))
rect.Resize(fyne.NewSize(20, 20))
return rect
}