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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package main

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

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

// defaultAltTextPrompt is what the prompt field is prefilled with. It is a
// default rather than a fixed instruction: the page hands back whatever it
// currently holds, edited or not, and that is what gets sent.
//
// Its three clauses each buy something, which is worth knowing before editing
// one away: "suitable for Mastodon" sets register, "max 1500 chars" is the
// platform's hard limit on the field, and "output only the alt text" is what
// suppresses the "Here is the alt text:" preamble the model otherwise offers.
const defaultAltTextPrompt = "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."

// variantCount is how many alt texts we generate per image. All of them use the
// same prompt; the variety comes from variantTemperature alone (see below).
const variantCount = 3

// variantTemperature is deliberately above Gemini's 1.0 default. With identical
// prompts and the default temperature the three candidates come back nearly
// word-for-word identical, which defeats the point of offering a choice. 1.3
// reliably changes sentence order and framing while staying accurate to the
// image; higher values start inventing details that are not in the picture.
const variantTemperature = 1.3

// geminiTimeout bounds a single generation. The three run concurrently, so this
// is also roughly the worst case for the whole batch.
const geminiTimeout = 90 * time.Second

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

type generationConfig struct {
	// Pointer so that a zero temperature would still be transmitted; Go's
	// omitempty would otherwise silently drop it.
	Temperature    *float64        `json:"temperature,omitempty"`
	ThinkingConfig *thinkingConfig `json:"thinkingConfig,omitempty"`
}

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

type content struct {
	// Role is "user" or "model". Gemini rejects a multi-turn request whose
	// turns are not labelled, so this is not optional once a conversation has
	// more than one entry.
	Role  string `json:"role,omitempty"`
	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"`
		FinishReason string `json:"finishReason"`
	} `json:"candidates"`
	Error *struct {
		Message string `json:"message"`
	} `json:"error"`
}

// initialHistory is the opening turn: the image plus the standing instruction
// to caption it.
//
// The prompt is passed in rather than read from the constant because it is
// editable in the page. Regenerating with a changed prompt calls this again
// with the same image, which is what makes it a genuinely fresh start rather
// than a refinement: nothing of the previous conversation survives.
func initialHistory(imageBytes []byte, mimeType string, prompt string) []content {
	return []content{{
		Role: "user",
		Parts: []part{
			{InlineData: &inlineData{
				MimeType: mimeType,
				Data:     base64.StdEncoding.EncodeToString(imageBytes),
			}},
			{Text: prompt},
		},
	}}
}

// appendTurn extends a conversation with the text that was chosen and the
// instruction for improving it.
//
// Only the chosen variant is recorded, never the rejected ones: the model
// should be working from the wording you settled on, not from a menu it might
// average over. The image stays where it is, in the first turn, so every
// refinement still sees the picture and can be checked against it rather than
// only against the previous description.
func appendTurn(history []content, chosen, instruction string) []content {
	// Copy rather than append in place: the caller keeps the old history, and
	// append would otherwise be free to write through a shared backing array.
	next := make([]content, len(history), len(history)+2)
	copy(next, history)
	return append(next,
		content{Role: "model", Parts: []part{{Text: chosen}}},
		content{Role: "user", Parts: []part{{Text: instruction}}},
	)
}

// generateAltText performs one generation from a conversation.
func generateAltText(ctx context.Context, apiKey string, history []content) (string, error) {
	temp := variantTemperature

	body := requestBody{
		Contents: history,
		GenerationConfig: &generationConfig{
			Temperature: &temp,
			// Thinking costs multiple seconds and buys nothing for a caption of
			// a picture that is right there in the request.
			ThinkingConfig: &thinkingConfig{ThinkingBudget: 0},
		},
	}

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

	req, err := http.NewRequestWithContext(ctx, "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 {
		return "", fmt.Errorf("no candidates in response")
	}

	cand := result.Candidates[0]
	if len(cand.Content.Parts) == 0 {
		// A candidate with no parts is how the API reports a safety block or a
		// token limit hit; the finish reason is the only useful signal there.
		if cand.FinishReason != "" && cand.FinishReason != "STOP" {
			return "", fmt.Errorf("generation stopped: %s", cand.FinishReason)
		}
		return "", fmt.Errorf("no content in response")
	}

	text := strings.TrimSpace(cand.Content.Parts[0].Text)
	if text == "" {
		return "", fmt.Errorf("empty alt text in response")
	}
	return text, nil
}

// variant is the outcome of one generation. Exactly one of Text and Err is set.
// A failed variant is reported to the page as an error card rather than
// aborting the batch, so one bad response does not cost you the other two.
type variant struct {
	Index int
	Text  string
	Err   error
}

// generateVariants runs variantCount generations of the same conversation
// concurrently and delivers each to emit as soon as it arrives, so the page
// fills in progressively instead of waiting for the slowest. emit is called
// from multiple goroutines and must be safe for concurrent use.
//
// All variantCount calls send the identical history; they differ only in
// sampling (see variantTemperature).
func generateVariants(ctx context.Context, apiKey string, history []content, emit func(variant)) {
	ctx, cancel := context.WithTimeout(ctx, geminiTimeout)
	defer cancel()

	var wg sync.WaitGroup
	for i := range variantCount {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			t0 := time.Now()
			text, err := generateAltText(ctx, apiKey, history)
			logf("variant %d: %s (%v)", i, time.Since(t0).Round(time.Millisecond), err)
			emit(variant{Index: i, Text: text, Err: err})
		}(i)
	}
	wg.Wait()
}

// apiKeyFromPass reads the key from the password store. This needs a working
// gpg-agent; under systemd that means GNUPGHOME must be set (see the unit).
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
}