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
- Variables
- func Detect(name string, head []byte) string
- func Duration(mime string, data []byte) float64
- func Expand(ctx context.Context, contents []*genai.Content, s *Store, route MediaPolicy, ...) ([]*genai.Content, error)
- func HasRefs(contents []*genai.Content) bool
- func IsAttachablePath(p string) bool
- func MentionedPaths(prompt string) []string
- func Mentions(prompt string) []string
- func Part(img *Image) *genai.Part
- func TypeForName(name string) string
- type Image
- type Kind
- type MediaPolicy
- type MediaType
- type Options
- type Route
- type Store
- func (s *Store) Dir() string
- func (s *Store) Get(uri string) ([]byte, string, error)
- func (s *Store) MIME(uri string) string
- func (s *Store) Pages(uri string) int
- func (s *Store) Path(uri string) (string, string, int64, error)
- func (s *Store) Prune(maxAge time.Duration) (int, error)
- func (s *Store) Put(img *Image) error
- func (s *Store) PutFile(name string, f io.ReaderAt, size int64) (*Image, error)
- func (s *Store) Text(ctx context.Context, uri string) (string, int, error)
- type Uploader
Constants ¶
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).
const ( MaxTextBytes = 1 << 20 MaxMediaBytes = 2 << 30 )
MaxTextBytes caps a text attachment; MaxMediaBytes an audio or video one (the Gemini Files API's limit).
const MaxDocumentText = 300_000
MaxDocumentText caps the text a model that can't read PDFs gets for one (about 75,000 tokens).
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.
const URIScheme = "blitz-image:"
URIScheme prefixes references to stored images ("blitz-image:<sha256>").
Variables ¶
var ErrNoClipboardImage = errors.New("no image on the clipboard")
ErrNoClipboardImage means the clipboard holds no image (or no clipboard tool is installed).
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.
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).
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
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
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 IsAttachablePath ¶ added in v0.2.1
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 ¶
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 ¶
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 TypeForName ¶ added in v0.2.1
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 ¶
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
IsDocument reports whether img is a PDF rather than a picture.
type Kind ¶ added in v0.2.1
type Kind string
Kind is what sort of attachment a file is.
type MediaPolicy ¶ added in v0.2.1
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
MediaType is a type of file Blitz attaches: its media type, kind and the extensions it goes by (the first is its usual one).
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 (*Store) MIME ¶ added in v0.2.1
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
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
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 ¶
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 ¶
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
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.