images

package
v0.8.2 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: Apache-2.0 Imports: 33 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_images_011).

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 MaxDocumentText = 300_000

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

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 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_images_011): 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 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.

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 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 IsImagePath

func IsImagePath(p string) bool

IsImagePath reports whether a file name has a supported image extension.

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 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 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.

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) 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