Profpatsch/users/Profpatsch/mastodon-alt-text/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
 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"time"
)

const geminiAPI = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"

const altTextPrompt = "Write alt text for this image suitable for Mastodon. Be descriptive but concise (max 1500 chars). Output only the alt text, no preamble or explanation."

type requestBody struct {
	Contents         []content         `json:"contents"`
	GenerationConfig *generationConfig `json:"generationConfig,omitempty"`
}

type generationConfig struct {
	ThinkingConfig *thinkingConfig `json:"thinkingConfig,omitempty"`
}

type thinkingConfig struct {
	ThinkingBudget int `json:"thinkingBudget"`
}

type content struct {
	Parts []part `json:"parts"`
}

type part struct {
	Text       string      `json:"text,omitempty"`
	InlineData *inlineData `json:"inline_data,omitempty"`
}

type inlineData struct {
	MimeType string `json:"mime_type"`
	Data     string `json:"data"`
}

type response struct {
	Candidates []struct {
		Content struct {
			Parts []struct {
				Text string `json:"text"`
			} `json:"parts"`
		} `json:"content"`
	} `json:"candidates"`
	Error *struct {
		Message string `json:"message"`
	} `json:"error"`
}

func readImageFromClipboard() ([]byte, error) {
	for _, mimeType := range []string{"image/png", "image/jpeg"} {
		cmd := exec.Command("xclip", "-selection", "clipboard", "-t", mimeType, "-o")
		out, err := cmd.Output()
		if err == nil && len(out) > 0 {
			return out, nil
		}
	}
	return nil, fmt.Errorf("no image found in X11 clipboard (tried image/png and image/jpeg)")
}

func convertToWebP(imageBytes []byte) ([]byte, error) {
	cmd := exec.Command("magick", "-", "webp:-")
	cmd.Stdin = bytes.NewReader(imageBytes)
	out, err := cmd.Output()
	if err != nil {
		return nil, fmt.Errorf("magick convert: %w", err)
	}
	return out, nil
}

func generateAltText(apiKey string, imageBytes []byte, mimeType string) (string, error) {
	encoded := base64.StdEncoding.EncodeToString(imageBytes)

	body := requestBody{
		Contents: []content{
			{
				Parts: []part{
					{InlineData: &inlineData{MimeType: mimeType, Data: encoded}},
					{Text: altTextPrompt},
				},
			},
		},
		GenerationConfig: &generationConfig{
			ThinkingConfig: &thinkingConfig{ThinkingBudget: 0},
		},
	}

	bodyJSON, err := json.Marshal(body)
	if err != nil {
		return "", fmt.Errorf("marshal request: %w", err)
	}

	req, err := http.NewRequest("POST", geminiAPI, bytes.NewReader(bodyJSON))
	if err != nil {
		return "", fmt.Errorf("create request: %w", err)
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("x-goog-api-key", apiKey)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", fmt.Errorf("http request: %w", err)
	}
	defer resp.Body.Close()

	var result response
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return "", fmt.Errorf("decode response: %w", err)
	}

	if result.Error != nil {
		return "", fmt.Errorf("gemini API error: %s", result.Error.Message)
	}

	if len(result.Candidates) == 0 || len(result.Candidates[0].Content.Parts) == 0 {
		return "", fmt.Errorf("no content in response")
	}

	return strings.TrimSpace(result.Candidates[0].Content.Parts[0].Text), nil
}

func apiKeyFromPass() (string, error) {
	out, err := exec.Command("pass", "internet/ai.google.dev/gemini/api-keys/gemini-2.5-flash").Output()
	if err != nil {
		return "", fmt.Errorf("pass: %w", err)
	}
	// pass outputs the key on the first line
	key := strings.SplitN(strings.TrimSpace(string(out)), "\n", 2)[0]
	return key, nil
}

func launch() {
	self, err := os.Executable()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}
	cmd := exec.Command("alacritty",
		"--class", "mastodon-alt-text,floating",
		"--title", "mastodon-alt-text",
		"-o", "window.dimensions.columns=90",
		"-o", "window.dimensions.lines=12",
		"--hold",
		"-e", self, "run",
	)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Start(); err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}
	// don't wait — detach and let alacritty manage its own lifecycle
}

func main() {
	if len(os.Args) > 1 && os.Args[1] == "run" {
		run()
		return
	}
	launch()
}

func run() {
	apiKey := os.Getenv("GEMINI_API_KEY")
	if apiKey == "" {
		var err error
		apiKey, err = apiKeyFromPass()
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: GEMINI_API_KEY not set and pass failed: %s\n", err)
			os.Exit(1)
		}
	}

	t0 := time.Now()

	imageBytes, err := readImageFromClipboard()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stderr, "clipboard read: %s\n", time.Since(t0).Round(time.Millisecond))

	t1 := time.Now()
	webpBytes, err := convertToWebP(imageBytes)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stderr, "webp convert: %s (%d KB → %d KB)\n", time.Since(t1).Round(time.Millisecond), len(imageBytes)/1024, len(webpBytes)/1024)

	t2 := time.Now()
	altText, err := generateAltText(apiKey, webpBytes, "image/webp")
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stderr, "gemini: %s\n", time.Since(t2).Round(time.Millisecond))
	fmt.Fprintf(os.Stderr, "total: %s\n", time.Since(t0).Round(time.Millisecond))

	fmt.Println(altText)

	cmd := exec.Command("xclip", "-selection", "primary")
	cmd.Stdin = strings.NewReader(altText)
	if err := cmd.Run(); err != nil {
		fmt.Fprintf(os.Stderr, "warning: failed to copy to primary selection: %s\n", err)
	}
}