pixlub

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 27 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.

README

pixlub-go

Official Go client for the Pixlub API. Go 1.23+, standard library only.

Documentation: getting started with the API and every module, its inputs and settings.

Install

go get github.com/pixlub/pixlub-go

Quick start

  1. Create an API key in your Pixlub dashboard. API keys need a paid plan.

  2. Put it in an environment variable, never in your source code:

    export PIXLUB_API_KEY="pix.xxxxxxxx.xxxxxxxx..."
    
  3. Run a tool:

    package main
    
    import (
        "context"
        "log"
    
        pixlub "github.com/pixlub/pixlub-go"
    )
    
    func main() {
        client, err := pixlub.NewClient()
        if err != nil {
            log.Fatal(err)
        }
        result, err := client.Tools.Run(context.Background(), "removeBgApi", pixlub.RunRequest{
            Image: pixlub.FromPath("photo.jpg"),
        })
        if err != nil {
            log.Fatal(err)
        }
        if err := result.Save("photo-nobg"+result.Extension(), false); err != nil {
            log.Fatal(err)
        }
    }
    

result.Extension() matches the produced file: .webp for removeBgApi, .png for most tools. Save refuses to replace an existing file unless overwrite is true.

Results

result.Image()          // bytes of the produced file (nil if the tool only returns data)
result.Data(&faces)     // the data output, decoded as JSON
result.Cost             // *int64: credits charged
result.CreditsBalance   // *int64: credits left
result.Output("out")    // an output by key, or by name ("image", "data", "file")
for _, out := range result.Outputs {
    fmt.Println(out.Key, out.Name, out.ContentType, out.Bytes)
}

In a batch, output keys get the rank of the file: out#0, out#1… Each Output.URL is a download link valid for one hour.

Tools and settings

tools, err := client.Tools.List(ctx, pixlub.ListOptions{ExecutableOnly: true})
schema, err := client.Tools.Schema(ctx, "flip") // JSON Schema of the settings

client.Tools.Run(ctx, "flip", pixlub.RunRequest{
    Image:  pixlub.FromPath("photo.jpg"),
    Params: map[string]any{"axis": "v"},
})

Invalid settings fail with ErrInvalidRequest, with the reasons in APIError.Details.

Several files

A tool with several inputs takes Inputs, keyed by input id. An input that takes several files (ToolInput.Multiple) takes a list in InputLists:

client.Tools.Run(ctx, "mask", pixlub.RunRequest{
    Inputs: map[string]pixlub.Source{
        "image": pixlub.FromPath("photo.png"),
        "mask":  pixlub.FromPath("mask.png"),
    },
})

client.Tools.Run(ctx, "merge", pixlub.RunRequest{
    Inputs:     map[string]pixlub.Source{"base": pixlub.FromPath("bg.png")},
    InputLists: map[string][]pixlub.Source{"overlay": {pixlub.FromPath("1.png"), pixlub.FromPath("2.png")}},
})

When ToolInput.PerFile is true, each file is a separate run, charged separately. A palette is passed in Params, as a list of colors.

A file comes from FromPath, FromBytes, FromReader or FromReaderSize. To use a file from the web, pass FromURL("https://..."); a path is always local. Large files are handled automatically.

Limits

Limit Value
File size, by plan Free 10 MiB, Basic 50 MiB, Pro 3 GiB
File size, by tool images 1 GiB, video and audio 3 GiB, Office 250 MiB
Image size 40 megapixels
Files per run 64
Runs 30 a minute per account, bursts of 10
Download links 1 hour
Results the SDK downloads 1 GiB per file, 4 GiB per run (larger: use the link)

Timeouts

Run waits for long runs until they finish, up to WithJobTimeout (30 minutes by default), within the deadline of the context. After that it fails with ErrJobTimeout: the run may still finish and may have been charged, so check it with GET /v1/jobs/{job_id} rather than running the tool again.

client, _ := pixlub.NewClient(pixlub.WithTimeout(30*time.Second), pixlub.WithJobTimeout(time.Hour))
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()

Errors

Test errors with errors.Is, and read the details with errors.As into *pixlub.APIError (HTTPStatus, Code, Message, MaxBytes, MaxPixels, Limit, RequiredCredits, RetryAfter, JobID) or *pixlub.ConnectionError (RequestSent).

Sentinel When
ErrConfiguration Missing or malformed key or base URL.
ErrInvalidInput An argument was refused before anything was sent.
ErrUnknownTool Unknown tool id.
ErrFileTooLarge A file is too large for the tool or your plan.
ErrInvalidRequest HTTP 4xx: invalid settings, image_too_large…
ErrAuthentication HTTP 401: unknown or revoked key.
ErrInsufficientCredits HTTP 402: not enough credits.
ErrPermissionDenied HTTP 403: not included in your plan.
ErrNotFound HTTP 404.
ErrRateLimited HTTP 429: too many requests. Never charged.
ErrServer HTTP 5xx.
ErrConnection, ErrTimeout No answer.
ErrJobTimeout A run outlived WithJobTimeout.
ErrUnexpectedResponse The answer could not be read.
result, err := client.Tools.Run(ctx, "removeBgApi", req)
var apiErr *pixlub.APIError
switch {
case errors.Is(err, pixlub.ErrInsufficientCredits):
    log.Println("top up your credits")
case errors.As(err, &apiErr):
    log.Printf("refused (%d): %s", apiErr.HTTPStatus, apiErr.Message)
case err != nil:
    log.Println("run failed:", err)
}

Retries and credits

The SDK retries a request only when it cannot cause a second charge, up to WithMaxRetries times (2 by default, 0 to disable), and waits as long as the API asks. Arguments are checked before anything is sent: a mistake costs nothing. After a timeout or a server error on a run, check your balance before running it again.

Configuration

Option Environment variable Default
WithAPIKey PIXLUB_API_KEY required
WithBaseURL PIXLUB_BASE_URL https://api.pixlub.com (http:// only for localhost)
WithTimeout 5 minutes per request
WithJobTimeout 30 minutes
WithMaxRetries 2 (0 to 5)
WithMaxInputBytes 3 GiB
WithHTTPClient a new http.Client (pass one for proxies or custom TLS)

Examples

examples/quickstart lists the tools, or removes the background of an image given on the command line.

Development

make check   # format, vet, race tests, example build
make live    # live tests: PIXLUB_API_KEY, PIXLUB_BASE_URL, and PIXLUB_LIVE_IMAGE to run a tool (costs credits)

License

MIT: see LICENSE.

Documentation

Overview

Package pixlub is the official Go client for the Pixlub API.

import pixlub "github.com/pixlub/pixlub-go"

client, err := pixlub.NewClient() // reads PIXLUB_API_KEY
if err != nil {
	log.Fatal(err)
}
result, err := client.Tools.Run(ctx, "removeBgApi", pixlub.RunRequest{
	Image: pixlub.FromPath("photo.jpg"),
})
if err != nil {
	log.Fatal(err)
}
if err := result.Save("photo-nobg"+result.Extension(), false); err != nil {
	log.Fatal(err)
}

A Client is safe for concurrent use: create one and reuse it. Large files are uploaded automatically, and long runs are awaited until WithJobTimeout. Arguments are checked before anything is sent, so a mistake costs nothing.

Index

Constants

View Source
const (
	// APIKeyEnv is the environment variable read when no key is passed.
	APIKeyEnv = "PIXLUB_API_KEY"
	// BaseURLEnv is the environment variable read when no base URL is passed.
	BaseURLEnv = "PIXLUB_BASE_URL"
	// DefaultBaseURL is used when neither WithBaseURL nor BaseURLEnv is set.
	DefaultBaseURL = "https://api.pixlub.com"
)
View Source
const DirectUploadMaxBytes = 90 << 20

DirectUploadMaxBytes is the largest total of files sent in one request. Larger files are uploaded automatically.

View Source
const Version = "0.3.1"

Version is the version of this SDK. It is sent in the User-Agent header.

Variables

View Source
var (
	// ErrConfiguration means the API key or base URL is missing or invalid.
	// Nothing was sent.
	ErrConfiguration = errors.New("pixlub: configuration error")

	// ErrInvalidInput means an argument was refused locally. Nothing was sent.
	ErrInvalidInput = errors.New("pixlub: invalid input")

	// ErrUnknownTool means the tool id is not in the catalog. It also matches
	// ErrInvalidInput.
	ErrUnknownTool = fmt.Errorf("%w: unknown tool", ErrInvalidInput)

	// ErrFileTooLarge means a file is too large, locally or for the tool or your
	// plan (HTTP 413, see APIError.MaxBytes).
	ErrFileTooLarge = errors.New("pixlub: file too large")

	// ErrNoData means the run produced no data output.
	ErrNoData = errors.New("pixlub: the run produced no data output")

	// ErrConnection means the API could not be reached, or the connection broke.
	ErrConnection = errors.New("pixlub: connection error")

	// ErrTimeout means the API did not answer in time. It also matches ErrConnection.
	ErrTimeout = fmt.Errorf("%w: timeout", ErrConnection)

	// ErrJobTimeout means a long run did not finish within the job timeout (see
	// WithJobTimeout). The run was accepted and may have been charged. It also
	// matches ErrTimeout.
	ErrJobTimeout = fmt.Errorf("%w: the job did not finish in time", ErrTimeout)

	// ErrUnexpectedResponse means the answer of the API could not be read.
	ErrUnexpectedResponse = errors.New("pixlub: unexpected response")

	// ErrAPI means the API answered with an error status. Every error below
	// matches it.
	ErrAPI = errors.New("pixlub: API error")

	// ErrInvalidRequest matches HTTP 4xx answers, such as invalid settings.
	ErrInvalidRequest = fmt.Errorf("%w: invalid request", ErrAPI)
	// ErrAuthentication matches HTTP 401: the key is unknown or revoked.
	ErrAuthentication = fmt.Errorf("%w: authentication failed", ErrAPI)
	// ErrPermissionDenied matches HTTP 403: the key is valid, but the account
	// may not do this, for example on a free plan.
	ErrPermissionDenied = fmt.Errorf("%w: permission denied", ErrAPI)
	// ErrNotFound matches HTTP 404.
	ErrNotFound = fmt.Errorf("%w: not found", ErrAPI)
	// ErrInsufficientCredits matches HTTP 402: not enough credits for the tool.
	ErrInsufficientCredits = fmt.Errorf("%w: insufficient credits", ErrAPI)
	// ErrRateLimited matches HTTP 429: too many requests. It is never charged.
	ErrRateLimited = fmt.Errorf("%w: rate limited", ErrAPI)
	// ErrServer matches HTTP 5xx: something failed on the server side.
	ErrServer = fmt.Errorf("%w: server error", ErrAPI)
)

Sentinel errors: test them with errors.Is, and read details with errors.As into *APIError or *ConnectionError.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	// HTTPStatus is the HTTP status code of the answer.
	HTTPStatus int
	// Code is the machine-readable code, such as "insufficient_credits", or "".
	Code string
	// Message is the message of the API.
	Message string
	// Details lists the invalid settings of an HTTP 400 answer, or is nil.
	Details any
	// RequiredCredits is the cost of the run (HTTP 402), or nil.
	RequiredCredits *int64
	// MaxBytes is the largest file accepted (HTTP 413), or nil.
	MaxBytes *int64
	// MaxPixels is the largest image accepted (Code "image_too_large"), or nil.
	MaxPixels *int64
	// Limit is the limit that was reached, such as the files of a batch for your
	// plan (Code "batch_limit"), or nil.
	Limit *int64
	// ResetAt is when a quota resets, when the API says so. It is zero otherwise.
	ResetAt time.Time
	// RetryAfter is how long to wait before trying again, or zero.
	RetryAfter time.Duration
	// JobID is the id of the long run that failed, or "".
	JobID string
	// contains filtered or unexported fields
}

APIError is an error answer of the API.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is makes an HTTP 413 answer match ErrFileTooLarge, besides its category.

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap returns the category sentinel, such as ErrRateLimited.

type Client

type Client struct {

	// Tools lists, describes and runs tools.
	Tools *Tools
	// contains filtered or unexported fields
}

Client talks to the Pixlub API. Create one with NewClient and reuse it. It is safe for concurrent use.

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient checks the configuration and returns a Client.

func (Client) GoString

func (c Client) GoString() string

GoString is the %#v form of String.

func (Client) String

func (c Client) String() string

String describes the client, with its key masked.

type ConnectionError

type ConnectionError struct {
	// Message explains the failure.
	Message string
	// RequestSent is true when the run may have been charged: check your
	// balance before running it again.
	RequestSent bool
	// contains filtered or unexported fields
}

ConnectionError means no usable answer came from the API.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

Unwrap returns ErrConnection or ErrTimeout.

type ListOptions

type ListOptions struct {
	// ExecutableOnly leaves out tools that cannot be run through the API.
	ExecutableOnly bool
}

ListOptions filters the result of Tools.List.

type Option

type Option func(*settings)

Option configures a Client. Pass options to NewClient.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API key. The default is PIXLUB_API_KEY.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets the address of the API. The default is PIXLUB_BASE_URL, then https://api.pixlub.com. Plain http is accepted only for localhost.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient uses this *http.Client, for proxies or custom TLS settings. Its timeout, if any, becomes the default of WithTimeout.

func WithJobTimeout

func WithJobTimeout(timeout time.Duration) Option

WithJobTimeout sets how long Run waits for a long run. The default is 30 minutes. After that, Run fails with ErrJobTimeout: the run may still finish, and may have been charged.

func WithMaxInputBytes

func WithMaxInputBytes(n int64) Option

WithMaxInputBytes sets the largest local file accepted. The default is 3 GiB.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets how many times a request is retried, from 0 to 5. The default is 2. A request that may have been charged is never retried.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets how long one request may wait. The default is five minutes. Use the context of each call to bound the whole call.

type Output

type Output struct {
	// Key is the tool output (see Tool.Outputs), such as "out". In a batch it
	// ends with the rank of the file: "out#0", "out#1"...
	Key string
	// Name is "image" (the produced image), "data" (JSON) or "file" (another format, such as a PDF).
	Name string
	// URL is the download link, valid for one hour.
	URL string
	// ContentType is the media type of Content, such as "image/png".
	ContentType string
	// Bytes is the size of the file, len(Content).
	Bytes int64
	// Content holds the bytes of the file.
	Content []byte
}

Output is one file of a run, already downloaded.

func (*Output) Extension

func (o *Output) Extension() string

Extension returns the file extension that matches the content type, such as ".png".

func (*Output) Save

func (o *Output) Save(path string, overwrite bool) error

Save writes the content to path, readable by its owner only. It refuses to replace a file unless overwrite is true.

type Result

type Result struct {
	// Module is the id of the tool that ran.
	Module string
	// ID identifies the run. Quote it when you contact support.
	ID string
	// JobID identifies a long run, or is empty.
	JobID string
	// Outputs lists every file of the run, in the order the API gave them.
	Outputs []Output
	// ExpiresAt is when the download links expire.
	ExpiresAt time.Time
	// Cost is the number of credits the run charged, when the API reports it.
	Cost *int64
	// CreditsBalance is what is left on the account after the run, when reported.
	CreditsBalance *int64
	// Message is an optional note from the tool, such as a warning about the result.
	Message string
}

Result is what a run produced. Outputs lists every file, already downloaded.

func (*Result) Data

func (r *Result) Data(v any) error

Data decodes the "data" output as JSON into v. It fails with ErrNoData when the tool returned no data.

func (*Result) Extension

func (r *Result) Extension() string

Extension returns the file extension of the produced file, such as ".png" or ".webp" (removeBgApi), or ".json" when the run produced only data.

func (*Result) File

func (r *Result) File() *Output

File returns the produced file: the image, or else the first output that is not data. It returns nil when the run produced neither.

func (*Result) Image

func (r *Result) Image() []byte

Image returns the bytes of the produced file, or nil when the tool only returns data.

func (*Result) Output

func (r *Result) Output(keyOrName string) *Output

Output returns the output with this key, such as "out" or "out#1", or else the first output with this name ("image", "data" or "file"). It returns nil when there is neither.

func (*Result) Save

func (r *Result) Save(path string, overwrite bool) error

Save writes the produced file to path. It refuses to replace a file unless overwrite is true.

type RunRequest

type RunRequest struct {
	// Image is the file of a tool that takes one input.
	Image Source
	// Inputs gives one file per input name.
	Inputs map[string]Source
	// InputLists gives several files per input name, for inputs that take
	// several (ToolInput.Multiple), up to ToolInput.MaxFiles each, and 64 files
	// per run in all. A name may be in Inputs or in InputLists, not in both.
	InputLists map[string][]Source
	Params     map[string]any
}

RunRequest describes one run. Set Image for a tool with a single input, or Inputs and InputLists for inputs keyed by name (see Tool.Inputs). Params holds the tool's settings, as JSON values (see Tools.Schema).

type Source

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

Source is one input file. Build it with FromPath, FromBytes, FromReader, FromReaderSize or FromURL. The zero value means "not set".

func FromBytes

func FromBytes(name string, data []byte) Source

FromBytes sends a file already in memory. name is optional.

func FromPath

func FromPath(path string) Source

FromPath sends the local file at path.

func FromReader

func FromReader(name string, reader io.Reader) Source

FromReader sends everything reader returns. name is optional. A reader that cannot seek is copied first; use FromPath for a file on disk.

func FromReaderSize

func FromReaderSize(name string, reader io.Reader, size int64) Source

FromReaderSize sends exactly size bytes read from reader. name is optional.

func FromURL

func FromURL(rawURL string) Source

FromURL uses a public https URL as the main input of the tool, instead of a local file: port 443, no credentials, 2048 characters at most.

type Tool

type Tool struct {
	// ID is the identifier to pass to Tools.Run, such as "removeBgApi".
	ID          string
	Name        string
	Description string
	Category    string
	// Executable is false when the tool cannot be run through the API.
	Executable bool
	// Handler is "local", "remote" or "none".
	Handler string
	// Inputs lists the file inputs. Pass them by name with RunRequest.Inputs,
	// or RunRequest.InputLists for several files.
	Inputs []ToolInput
	// Outputs lists the files a run may produce, by key (see Output.Key).
	Outputs []ToolOutput
}

Tool is a tool of the catalog returned by Tools.List.

type ToolInput

type ToolInput struct {
	// ID is the name to use as a key of RunRequest.Inputs or RunRequest.InputLists.
	ID          string
	Label       string
	Description string
	// Required is true when the tool cannot run without this input.
	Required bool
	// Type is "image", "channel" (read as grayscale), "batch" or another kind
	// of file the tool reads. A palette is not a file: its colors go in Params.
	Type string
	// Multiple is true when the input takes several files: pass them with
	// RunRequest.InputLists.
	Multiple bool
	// PerFile is true when each file of the input is a run of its own, charged
	// on its own: a batch. Its outputs are keyed by rank, such as "out#0".
	PerFile bool
	// MaxFiles is the most files the input takes in one run, for your plan, or 0.
	MaxFiles int
	// Accept lists the media types the input takes, such as "image/png".
	Accept []string
}

ToolInput is one file input of a tool.

type ToolOutput

type ToolOutput struct {
	// Key identifies the output in Result.Outputs (Output.Key). In a batch,
	// each file is keyed with its rank: "out#0", "out#1"...
	Key         string
	Label       string
	Description string
	// Kind is the kind of file, such as "image" or "data".
	Kind string
	// Multiple is true when a run may produce several files for this key.
	Multiple bool
	// ContentTypes lists the media types the output may have.
	ContentTypes []string
}

ToolOutput is one kind of file a tool produces.

type Tools

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

Tools lists, describes and runs tools. Access it as client.Tools.

func (*Tools) List

func (t *Tools) List(ctx context.Context, opts ListOptions) ([]Tool, error)

List returns the tools.

func (*Tools) Retrieve

func (t *Tools) Retrieve(ctx context.Context, id string) (*Tool, error)

Retrieve returns one tool, or ErrUnknownTool.

func (*Tools) Run

func (t *Tools) Run(ctx context.Context, id string, req RunRequest) (*Result, error)

Run runs a tool and downloads every file it produced. Large files are uploaded automatically, and a long run is awaited until WithJobTimeout. Set a deadline on ctx to bound the whole call.

func (*Tools) Schema

func (t *Tools) Schema(ctx context.Context, id string) (map[string]any, error)

Schema returns the JSON Schema of a tool's Params.

Directories

Path Synopsis
examples
quickstart command
Command quickstart lists the tools of the Pixlub API, and runs one on an image.
Command quickstart lists the tools of the Pixlub API, and runs one on an image.

Jump to

Keyboard shortcuts

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