# google-apis.md

> Source: <https://gist.github.com/hadley/ced3f7e919a89baf4ad96a8ace252b24>
> Published: 2026-10-19 12:52:01+00:00

**Key takeaway:** Gemini image, TTS, music and transcription calls all go through POST /models/<id>:generateContent with the key in x-goog-api-key, and because TTS caps at 10 requests per minute with 429 retryDelay values near 60s, throttle parallel calls and start TTS early rather than relying on short backoffs.

- 
**The API key wasn't in the shell environment.** It lives in`~/.Renviron` , so the
scripts fall back to reading`GOOGLE_API_KEY` from there.
- 
**Find model IDs by listing them, not by guessing marketing names:**`GET https://generativelanguage.googleapis.com/v1beta/models?pageSize=200` (the`displayName` field maps the two). The ones used:Want Model ID `displayName` Image generation `gemini-3.1-flash-image` Nano Banana 2 Text-to-speech `gemini-3.8-flash-tts` (also`-lite-tts` )Gemini 3.8 Flash TTS Music `lyria-3.5` Lyria 3.5 Transcription / QA `gemini-3.8-flash`
- 
**All four use the same `POST .../models/<id>:generateContent` endpoint** , with the key
in the`x-goog-api-key` header. Output comes back base64-encoded in`candidates[0].content.parts[].inlineData` as`{mimeType, data}` .
- 
**Rate limits are per model and low.** TTS allowed 10 requests per minute. Going over
returns a 429`RESOURCE_EXHAUSTED` that says how long to wait (around 40s). Short
retry backoffs of a few seconds aren't enough, so either throttle parallel calls or
honour that delay. The 429 body includes a`"retryDelay": "57s"` field, and parsing it
worked well. Four parallel TTS workers still hit several of these waits of about 60s
each, so 11 short clips took about 4 minutes. Start TTS early and do other work while
it runs.
- 
**Other models in the list:**`gemini-3-pro-image` (Nano Banana Pro),`gemini-3.1-flash-lite-image` (Nano Banana 2 Lite) and`lyria-3-pro-preview` . None of
them has been tried yet.
- 
**A small shared client helps.**`video/tools/gapi.py` has`image()` ,`tts()` ,`music()` and`transcribe()` . It retries 429 and 5xx errors and appends each call's`usageMetadata` to`video/api-log.jsonl` , which makes cost estimates easy afterwards.

- **Request shape:**`generationConfig: { responseModalities: ["IMAGE"], imageConfig: { aspectRatio: "16:9", imageSize: "2K" } }` .`"1K"` is fine for cutouts, and`"2K"` suits full-frame 1080p backgrounds.
- **Reference images work very well.** Add the reference as an extra`inlineData` part
in the same request. It kept a mascot consistent across four poses ("the exact same
character from the reference image, now…"), and it turned the package's flat hex logo
into a clay version with the word "genzplyr" spelled correctly.
- **A shared style prefix on every prompt keeps a set of images coherent.** Here that
was: stop-motion claymation, visible fingerprints, a pastel palette and soft studio
light. Another round used a glossy 3D vinyl toy look with Y2K styling, pastel colours and
chrome accents.
  - **A character-flavoured style prefix leaks into backgrounds.** With a "vinyl toy"
prefix, 2 of 3 background prompts came back with a random toy character in the
middle. Adding "no characters, no creatures, no toys, no people" fixed it on the
first retry.
- **Reference-based poses were consistent across 9 variants.** The mascot kept its body,
colours and accessories when shown throwing, holding a magnifying glass, dressed as a
ghost and so on. "Three identical siblings in different colours" also worked.
- **Generating 5 images in parallel was fine.** There were no 429s from the image model,
and each image took about 20–40s.
- **Transparent backgrounds:** ask for a "perfectly flat pure chroma-key green (#00FF00)
background" and say the object contains no green. But:
  - **The green is never actually #00FF00.** Across one batch it ranged from`#06a82e` to`#40c352` , and some backgrounds had a subtle gradient.
  - **ffmpeg `colorkey` wasn't reliable,** even when keyed on a colour sampled from each
image: lavender and grey subjects went semi-transparent.
  - **A green-dominance matte works.** Set alpha from how much green exceeds max(red,
blue), and clamp green spill. See`video/tools/key.py` , which has this in about 15
lines of numpy and crops each cutout to its bounding box. The values`alpha = 1 - clip((excess - 25) / 60)` and a despill of`g = min(g, max(r, b) + 8)` gave clean edges on 11 cutouts, including sparkles and a translucent white ghost
sheet.
- **Text in background images:** the model sometimes adds readable text even when asked
not to (for example a neon "HEART" sign).

- **Request shape:**`generationConfig: { responseModalities: ["AUDIO"], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: "Zephyr" } } } }` .
- **Output is raw 16-bit mono PCM,** not a WAV file. Wrap it with`ffmpeg -f s16le -ar 24000 -ac 1 -i in.pcm out.wav` . The sample rate is parsed from
the`mimeType` , with 24 kHz assumed as the fallback.
- **Style directions are the big gotcha:**  - **Plain instructions get read aloud.** "Say fast and sassy, like…: " produced
a clip that spoke the instructions and then the line. The first attempt made 18–21s
clips for 4–7s lines.
  - **`systemInstruction` isn't an alternative.** It's rejected with 400 "Developer
instruction is not enabled for this model".
  - **A structured prompt works.** The model speaks only what follows the transcript
heading:

```
# AUDIO PROFILE: <name>
<one-line persona>

### DIRECTOR'S NOTES
Style: ...
Only the transcript below is spoken aloud.

#### TRANSCRIPT
<the line>
```

- **Pronunciation is fixed by respelling.** "genzplyr" became "gen Z plier", "dplyr"
became "dee plier", and "pak" became "Pack". Slang such as "periodt" and "fr fr" is
delivered well, but may come out closer to "period" / "FFR".
- **Generate one clip per line.** That makes scene timing easy. Trim leading and
trailing silence with ffmpeg`silenceremove` , measure each clip with`ffprobe` , and
size scenes to the results. The same voice and prompt sounded consistent from line to
line.
- **Pick a voice by having Gemini compare candidates.** Generate the same line with a few
voices and send all the clips in one`gemini-3.8-flash` request. Put a text label before
each clip ("Clip 1:" and so on), then ask for a transcript, a 1–10 fit rating and the
best clip. For a "bubbly, sassy Gen Z creator" it ranked Zephyr (9) over Fenrir (7),
Laomedeia (6.5) and Puck (5).
- **Delivery runs slow for short-form video.** About 150 words came to 56s even with "fast
pace" in the director's notes.`ffmpeg -af atempo=1.1` gave a snappier result with no
audible artefacts reported by the QA pass. Write about 10% fewer words than you think
you need.
- **Respelling "pak" as "pack" worked.** The transcriber heard "pak". "Periodt" was again
transcribed as "Period".

- **One `generateContent` call with just a text prompt** returned an`audio/mpeg` track.
Asking for 60 seconds gave 62s.
- **"No vocals" isn't strictly obeyed.** The track included a couple of shouted "Hey!"
samples. They're fine here, but listen before relying on it.
- **Describing tempo, instruments, mood and "steady energy so it sits under a
voiceover"** gave a usable bed track on the first try. It mixed well at about 22%
volume under the VO.
- **"Strictly instrumental, no vocals, no vocal chops"** gave a track that Gemini
described as fully instrumental. Its full-video QA later mentioned "minor processed
vocal chops/risers", so it's still worth checking.
- **Tempo and genre are loose suggestions.** Asking for a 140 BPM Jersey club beat gave
a four-on-the-floor dance track at about 128 BPM, according to Gemini. It was still a
good bed, but don't sync animation to the requested BPM without measuring it. Asking
for 60 seconds gave 63s.
- **Sidechain ducking beats a fixed music volume.** In ffmpeg, pass the music and the VO
through`sidechaincompress=threshold=0.03:ratio=4:attack=15:release=350` , then`amix` and`loudnorm=I=-14` . That lets the music sit louder (0.32) between lines. See`video/tools/mix.sh` .

Sending generated audio back to `gemini-3.8-flash` with "Transcribe verbatim with
timestamps, then one sentence on delivery" was the fastest way to catch problems
without listening:

- the TTS speaking its instructions aloud;
- mispronunciations;
- vocals in the music.

Running it on the final mix confirmed the VO was intelligible over the music. The transcriber makes its own mistakes, though: it heard "Rows" as "Bros" and "dplyr" as "deep player". Read its output as a hint, not ground truth.

**Whole-video QA works too.** Send a 640×360 MP4 inline (`mimeType: "video/mp4"`, a few
MB) with questions about the VO transcript, intelligibility, caption sync and visual
glitches. It caught a real timing problem, where elements popped in too late on short
cards. But at that resolution it **invented typos in on-screen code** ("no_tap",
"JO!NS", a stray quote) that weren't there. Always check reported text problems
against full-resolution frames pulled with `ffmpeg -ss <t> -frames:v 1`.
