images

package
v0.9.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 34 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package images prepares pictures and PDFs for models and keeps them out of session files.

An image is normalised once (format checked, oversized pictures scaled down and re-encoded), written to a content-addressed Store and referred to in conversation history by a FileData part whose URI starts with URIScheme. Session files therefore hold a short reference instead of megabytes of base64; Expand swaps the references for the bytes just before each model request. A PDF is kept as it is, with its page count; Expand gives it to a model that reads PDFs as is, and to others as its text (spec_011_images).

Index

Constants

View Source
const (
	DefaultMaxDimension = 1568
	DefaultMaxInput     = 20 << 20
	MaxEncodedBytes     = 3_750_000
	// MaxDocumentBytes is the largest PDF accepted, Anthropic's request
	// limit.
	MaxDocumentBytes = 32 << 20
)

Defaults suit every supported provider: Anthropic recommends at most 1568 pixels on the long edge and caps images at 5 MB (3.75 MB before base64).

View Source
const (
	MaxTextBytes  = 1 << 20
	MaxMediaBytes = 2 << 30
)

MaxTextBytes caps a text attachment; MaxMediaBytes an audio or video one (the Gemini Files API's limit).

View Source
const (
	// KindGemini answers with text and one picture a turn, takes
	// references and keeps a conversation (generateContent).
	KindGemini = "gemini"
	// KindImagen makes 1 to 4 pictures from text alone (generateImages).
	KindImagen = "imagen"
	// KindOpenAI is an OpenAI image model: 1 to 4 pictures a request,
	// from text (images/generations) or starting from references
	// (images/edits), priced per picture (spec_058_pictures PIC-04).
	KindOpenAI = "openai"
)

The kinds of image model (spec_058_pictures §2).

View Source
const (
	RoleCharacter = "character"
	RoleObject    = "object"
	RoleStyle     = "style"
)

Reference roles (PIC-23).

View Source
const ImagenPromptTokens = 480

ImagenPromptTokens is the most an Imagen prompt may be, in tokens.

View Source
const MaxDocumentText = 300_000

MaxDocumentText caps the text a model that can't read PDFs gets for one (about 75,000 tokens).

View Source
const MaxReferenceBytes = 7 << 20

MaxReferenceBytes is the most a reference picture may be.

View Source
const ToolResultKey = "image_uri"

ToolResultKey marks a tool result that carries an image: its value is an Image.URI, and Expand places the picture right after the result.

View Source
const URIScheme = "blitz-image:"

URIScheme prefixes references to stored images ("blitz-image:<sha256>").

Variables

View Source
var (
	StandardRatios  = []string{"1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"}
	PanoramicRatios = []string{"1:4", "4:1", "1:8", "8:1"}
	ImagenRatios    = []string{"1:1", "3:4", "4:3", "9:16", "16:9"}
)

Ratio sets (PIC-02).

View Source
var ErrNoClipboardImage = errors.New("no image on the clipboard")

ErrNoClipboardImage means the clipboard holds no image (or no clipboard tool is installed).

View Source
var ErrNotImage = errors.New("not a file Blitz can attach (an image, a PDF, a text file, audio or video)")

ErrNotImage is returned for data that isn't a type Blitz attaches.

View Source
var Media = []MediaType{
	{"image/png", KindImage, []string{".png"}},
	{"image/jpeg", KindImage, []string{".jpg", ".jpeg"}},
	{"image/gif", KindImage, []string{".gif"}},
	{"image/webp", KindImage, []string{".webp"}},
	{"image/bmp", KindImage, []string{".bmp"}},
	{"image/heic", KindImage, []string{".heic"}},
	{"image/heif", KindImage, []string{".heif"}},
	{pdftext.MIME, KindDocument, []string{".pdf"}},
	{"text/plain", KindText, textExts},
	{"audio/mpeg", KindAudio, []string{".mp3"}},
	{"audio/wav", KindAudio, []string{".wav"}},
	{"audio/aac", KindAudio, []string{".aac"}},
	{"audio/flac", KindAudio, []string{".flac"}},
	{"audio/ogg", KindAudio, []string{".ogg", ".oga"}},
	{"audio/opus", KindAudio, []string{".opus"}},
	{"audio/mp4", KindAudio, []string{".m4a"}},
	{"audio/webm", KindAudio, []string{".weba"}},
	{"video/mp4", KindVideo, []string{".mp4", ".m4v"}},
	{"video/quicktime", KindVideo, []string{".mov"}},
	{"video/mpeg", KindVideo, []string{".mpeg", ".mpg"}},
	{"video/webm", KindVideo, []string{".webm"}},
	{"video/x-msvideo", KindVideo, []string{".avi"}},
	{"video/x-ms-wmv", KindVideo, []string{".wmv"}},
	{"video/x-flv", KindVideo, []string{".flv"}},
	{"video/3gpp", KindVideo, []string{".3gp"}},
}

Media are the attachable types (spec_011_images): what the providers take as input, Gemini the most of them. Which a model takes is the engine's to say (runtime.AcceptedMedia).

View Source
var OpenAIRatios = []string{"1:1", "3:2", "2:3"}

OpenAIRatios are the shapes an OpenAI image model makes, and their sizes.

View Source
var PeopleSettings = []string{"DONT_ALLOW", "ALLOW_ADULT", "ALLOW_ALL"}

People settings (PIC-29).

View Source
var ReadClipboard = readClipboard

ReadClipboard returns the clipboard image as PNG bytes using the platform's own tools: osascript on macOS, wl-paste or xclip on Linux, and PowerShell on Windows. It is a variable so tests can replace it.

View Source
var ReferenceTypes = []string{"image/png", "image/jpeg", "image/webp"}

ReferenceTypes are the pictures a model starts from, and MaxReferenceBytes the most each may be (PIC-23).

Functions

func Detect added in v0.2.1

func Detect(name string, head []byte) string

Detect is the attachable type of a file, from its first bytes (at least 512 where it has them), its name breaking ties: WebM is audio by its extension, else video; a file is text only by its name, and only when it's UTF-8 without NULs. "" when it's none of them.

func Duration added in v0.2.1

func Duration(mime string, data []byte) float64

Duration is the length in seconds of WAV audio, or of an MP4, QuickTime, M4A or 3GPP file whose movie header (mvhd) is in data; 0 when data doesn't give it.

func EstimateTokens added in v0.9.4

func EstimateTokens(text string) int

EstimateTokens is about how many tokens text is (four characters each).

func Expand

func Expand(ctx context.Context, contents []*genai.Content, s *Store, route MediaPolicy, up Uploader) ([]*genai.Content, error)

Expand returns contents with stored-file references replaced by what the model about to answer takes, as route says (nil: Inline for images, Text for PDFs and text files, Note for audio and video): the bytes; a PDF's text in a <document> block or a text file's in a <file> block; a note; or a reference to the file uploaded with up. A tool result's file follows the result. Inputs are never modified: they are usually the session's own events. A missing file, or a nil store, becomes a short note instead so the request still works; an upload that fails is an error.

func HasRefs

func HasRefs(contents []*genai.Content) bool

HasRefs reports whether any content refers to a stored image.

func IsAttachablePath added in v0.2.1

func IsAttachablePath(p string) bool

IsAttachablePath reports whether a file name is one an @mention attaches rather than inlines: a picture, a PDF, audio or video. (Text files are inlined by the mention itself.)

func MentionedPaths

func MentionedPaths(prompt string) []string

MentionedPaths returns every @path in a prompt (images or not), in order and without duplicates; trailing punctuation isn't part of a bare path.

func Mentions

func Mentions(prompt string) []string

Mentions returns the files an @path in a prompt attaches (pictures and PDFs), in order and without duplicates. Other @paths are left for the model.

func Part

func Part(img *Image) *genai.Part

Part is the history reference for img.

func TypeForName added in v0.2.1

func TypeForName(name string) string

TypeForName is the attachable type a file name says ("" for none).

Types

type Image

type Image struct {
	Name          string // file name for people (no directory)
	Data          []byte
	MIME          string
	Width, Height int
	SHA256        string // of Data
	OriginalBytes int
	Resized       bool
	// Size is len(Data), kept for an image whose data stays elsewhere (one
	// held by the Blitz service).
	Size int
	// Pages is a PDF's page count; 0 for a picture.
	Pages int
	// Kind is what sort of attachment it is ("" for an image prepared
	// before kinds existed).
	Kind Kind
	// Seconds is the length of audio or video, when its header gives it
	// cheaply; 0 otherwise.
	Seconds float64
}

Image is a prepared picture.

func Prepare

func Prepare(name string, data []byte, o Options) (*Image, error)

Prepare validates data for the model, by its type (detected from the bytes, the name breaking ties: Detect). Images are checked and scaled down when larger than the limits allow, GIF and BMP made PNG (which every provider takes); HEIC and HEIF are kept as they are. A PDF (up to MaxDocumentBytes) is kept once it's known readable; text (up to MaxTextBytes), audio and video (up to the input limit; larger ones come from files, PrepareStream) as they are.

func (*Image) IsDocument added in v0.2.1

func (img *Image) IsDocument() bool

IsDocument reports whether img is a PDF rather than a picture.

func (*Image) Summary

func (img *Image) Summary() string

Summary is a short human description: "shot.png 1280×720, 210 KB".

func (*Image) URI

func (img *Image) URI() string

URI is the reference stored in conversation history.

type Kind added in v0.2.1

type Kind string

Kind is what sort of attachment a file is.

const (
	KindImage    Kind = "image"
	KindDocument Kind = "document" // a PDF
	KindText     Kind = "text"
	KindAudio    Kind = "audio"
	KindVideo    Kind = "video"
)

The kinds of attachment.

func KindOf added in v0.2.1

func KindOf(mime string) Kind

KindOf is the kind of an attachable media type ("" for none).

type MediaPolicy added in v0.2.1

type MediaPolicy func(mime string, size int64, pages int) Route

MediaPolicy routes a stored file of type mime, size bytes and (a PDF) pages for the model about to answer.

type MediaType added in v0.2.1

type MediaType struct {
	MIME string
	Kind Kind
	Exts []string
}

MediaType is a type of file Blitz attaches: its media type, kind and the extensions it goes by (the first is its usual one).

func MediaOf added in v0.2.1

func MediaOf(mime string) (MediaType, bool)

MediaOf is the attachable type with this media type (ok false for none).

type Model added in v0.9.4

type Model struct {
	ID   string
	Name string
	Kind string
	// Provider is whose credentials make it ("": gemini).
	Provider string
	// MaxReferences is the most references in all; MaxCharacters and
	// MaxObjects the most of each role (0: no cap of their own).
	MaxReferences int
	MaxCharacters int
	MaxObjects    int
	// MaxPictures is the most pictures a request makes.
	MaxPictures int
	// Sizes are the output sizes ("1K"…; none: the model's own, fixed).
	Sizes  []string
	Ratios []string
	// Thinking are its levels (MINIMAL, MEDIUM, HIGH; none: it doesn't
	// think, or not as a setting); ThinkingAlways: it always thinks.
	Thinking       []string
	ThinkingAlways bool
	// Search is its grounding: "" none, "web", or "image" (web and image).
	Search         string
	NegativePrompt bool
	People         bool
	Seed           bool
	Enhance        bool
	Formats        []string
	// SizeTokens are a picture's output tokens by size (Gemini), for
	// estimates; PerPicture is a picture's price in USD (Imagen).
	SizeTokens map[string]int
	PerPicture float64
	// SearchPerCall is a grounding search's price in USD (0: not known).
	SearchPerCall float64
	// Assumed marks a model the catalog doesn't know: its family's values.
	Assumed bool
}

Model is what an image model can do: what Pictures offers for it (spec_058_pictures PIC-01). It's data: the panel shows, locks and hides its controls from it, and the service checks requests against it.

func Lookup added in v0.9.4

func Lookup(id string) (Model, bool)

Lookup is what the model id ("provider/" prefix and all) can do: its catalog entry, else its family's most conservative values, marked Assumed (PIC-03). ok is false for a model that isn't an image model.

func Models added in v0.9.4

func Models() []Model

Models are the catalog's models, in its order (the default first).

func (Model) Check added in v0.9.4

func (m Model) Check(r Request) []string

Check says what in r m doesn't take, each with what it does (nil: all of it): the service's check before anything is sent (PIC-62).

func (Model) OutputTokens added in v0.9.4

func (m Model) OutputTokens(size string) int

OutputTokens are about what one picture of size costs in output tokens (Gemini; 0 when the catalog doesn't say).

func (Model) PricedPerPicture added in v0.9.6

func (m Model) PricedPerPicture() bool

PricedPerPicture reports whether m's price is per picture (Imagen's and OpenAI's), not by tokens (Gemini's).

func (Model) ProviderOf added in v0.9.6

func (m Model) ProviderOf() string

ProviderOf is the provider whose credentials m's calls use.

type Options

type Options struct {
	MaxDimension int   // longest edge after scaling (default 1568)
	MaxInput     int64 // largest file accepted (default 20 MB)
}

Options bound what Prepare accepts and produces.

type Reference added in v0.9.4

type Reference struct {
	Role string
	MIME string
	Size int
}

Reference is a picture a request starts from, with its role.

type Request added in v0.9.4

type Request struct {
	Prompt       string
	References   []Reference
	Count        int
	AspectRatio  string
	Size         string
	Thinking     string
	Search       bool
	SearchImages bool
	Avoid        string
	People       string
	Seed         bool
	Enhance      bool
	Format       string
	Quality      int
}

Request is what a Pictures turn asks for: what Check takes.

type Route added in v0.2.1

type Route int

Route is how a stored file goes to the model about to answer.

const (
	// RouteInline sends the bytes in the request.
	RouteInline Route = iota
	// RouteText sends text instead: a PDF's text, a text file's content.
	RouteText
	// RouteNote sends a note that the model can't take the file.
	RouteNote
	// RouteUpload sends a reference to the file in the provider's own
	// store (Gemini's Files API), uploading it first.
	RouteUpload
)

The routes.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store keeps prepared images and PDFs on disk, named by their SHA-256, readable only by the owner. Identical files are stored once; a PDF's text, once read, is kept beside it (<sha>.pdf.txt).

func OpenStore

func OpenStore(dir string) (*Store, error)

OpenStore creates dir (mode 700) if needed.

func (*Store) Dir

func (s *Store) Dir() string

Dir returns the store's directory.

func (*Store) Get

func (s *Store) Get(uri string) ([]byte, string, error)

Get loads a stored image by the URI from Image.URI.

func (*Store) MIME added in v0.2.1

func (s *Store) MIME(uri string) string

MIME is a stored file's media type, by its URI; "" when it isn't stored (or s is nil).

func (*Store) Pages added in v0.2.1

func (s *Store) Pages(uri string) int

Pages is a stored PDF's page count, by its URI; 0 when it isn't one (or s is nil).

func (*Store) Path added in v0.2.1

func (s *Store) Path(uri string) (string, string, int64, error)

Path is a stored file's path, media type and size, by its URI: for sending a large one without reading it all.

func (*Store) Prune

func (s *Store) Prune(maxAge time.Duration) (int, error)

Prune deletes images not used for maxAge and reports how many went. It also deletes temporary files a crash left behind (older than an hour; not counted), whatever maxAge is.

func (*Store) Put

func (s *Store) Put(img *Image) error

Put saves img unless an identical image is already stored, in which case its age is reset so pruning keeps it.

func (*Store) PutFile added in v0.2.1

func (s *Store) PutFile(name string, f io.ReaderAt, size int64) (*Image, error)

PutFile stores an audio or video file as it is, streamed (it may be as large as MaxMediaBytes), and returns it without its data (Size set): its type comes from its first bytes and its name (Detect), its length from its header when that's cheap.

func (*Store) PutMade added in v0.9.2

func (s *Store) PutMade(name, mime string, data []byte) (*Image, error)

PutMade stores a file a model made (an image, audio, a file a provider tool wrote: spec_056_conversation_adapters CA-70) as it is, named name, and returns it without its data (Size set). Its type must be one Blitz keeps (Media).

func (*Store) Text added in v0.2.1

func (s *Store) Text(ctx context.Context, uri string) (string, int, error)

Text is a stored PDF's text (see pdftext.Text) and page count, read once and then kept beside the PDF. A PDF whose text couldn't be read (it timed out, or is unreadable) isn't tried again by this process.

type Uploader added in v0.2.1

type Uploader func(ctx context.Context, path, mime, sha string) (*genai.FileData, error)

Uploader puts a stored file (path, of type mime, named by its SHA-256) in the provider's own store and returns its reference there.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL