Skip to main content

Bria.ai Python SDK

Project description

Bria Client

Python Version License

A Python client library for the Bria Engine API, designed to make integrating powerful image and video editing capabilities into your applications seamless and straightforward. The library provides both synchronous and asynchronous clients with flexible request execution modes.

Table of Contents

Installation

pip install bria-client

Quick Start

Set your API key:

export BRIA_API_TOKEN="your-api-key-here"

Basic example:

from bria_client import BriaSyncClient
from bria_client.toolkit.image import Image

client = BriaSyncClient()

# Process an image and get the result immediately
response = client.run(
    endpoint="image/edit/remove_background",
    payload={"image": Image("https://example.com/image.jpg").as_bria_api_input}
)

print(response.result)

Usage Guide

Two Client Types

Choose the client that fits your use case:

BriaSyncClient - For simple scripts and traditional applications

from bria_client import BriaSyncClient

client = BriaSyncClient()
response = client.run(endpoint="image/edit/remove_background", payload={...})

BriaAsyncClient - For async applications and concurrent processing

from bria_client import BriaAsyncClient

async def process_images():
    async with BriaAsyncClient() as client:
        response = await client.run(endpoint="image/edit/remove_background", payload={...})
    return response

Three Request Methods

.run() - Wait for immediate result

# Good for quick operations
response = client.run(endpoint="image/edit/remove_background", payload={...})
print(response.result)

.submit() - Submit and continue working

# Good for long operations - returns immediately with request_id
response = client.submit(endpoint="video/segment/mask_by_prompt", payload={...})
print(f"Submitted: {response.request_id}")
# Do other work...

.poll() - Wait for a submitted request to complete

# Check request status until done
response = client.submit(endpoint="...", payload={...})
final = client.poll(response, interval=2, timeout=300)
print(final.result)

Payload Handling

The client automatically strips None values from payloads before sending requests. This means you can safely include optional parameters without worrying about sending null values to the API:

response = client.run(
    endpoint="image/edit/remove_background",
    payload={
        "image": Image("https://example.com/image.jpg").as_bria_api_input,
        "bg_color": None,  # Will be omitted from the request
    }
)

Webhooks

Instead of polling, you can ask Bria to POST the result to your server as soon as a job completes. Pass webhook_url to .submit():

response = client.submit(
    endpoint="video/edit/remove_background",
    payload={"video": file_url},
    webhook_url="https://your-server.example.com/webhook",
)
print(f"Submitted: {response.request_id}")

Bria signs every delivery with HMAC-SHA256. Verify the signature before processing the payload:

from bria_client.toolkit import verify_webhook_signature

# In your webhook receiver (e.g. a FastAPI POST handler):
body = await request.body()
is_valid = verify_webhook_signature(
    payload=body,
    webhook_id=request.headers["bria-webhook-id"],
    timestamp=request.headers["bria-webhook-timestamp"],
    signature_header=request.headers["bria-webhook-signature"],
    api_token=os.environ["BRIA_API_TOKEN"],
)
if not is_valid:
    raise HTTPException(status_code=401, detail="Invalid webhook signature")

Best practices:

  • Respond with a 2xx status within 10 seconds — defer any heavy processing to a background task.
  • Always verify the signature before acting on the payload.

See examples/webhook_handler.py for a complete FastAPI receiver with optional ngrok tunnel for local development.

Video Upload

Video endpoints expect a hosted URL. If you have a local file, use client.upload() to get one via a presigned upload:

file_url = client.upload("path/to/video.mp4", media_type="video/mp4")

response = client.submit(
    endpoint="video/edit/remove_background",
    payload={"video": file_url},
)

result = client.poll(response, timeout=300)
print(result.result)

The returned file_url is valid for approximately 24 hours.

See examples/video_upload.py for the full example.

Examples

Basic Usage

from bria_client import BriaSyncClient
from bria_client.toolkit.image import Image

client = BriaSyncClient()

response = client.run(
    endpoint="image/edit/remove_background",
    payload={"image": Image("https://example.com/image.jpg").as_bria_api_input}
)

print(response.result)

Batch Processing

from bria_client import BriaSyncClient
from bria_client.toolkit.image import Image

client = BriaSyncClient()
images = ["image1.jpg", "image2.jpg", "image3.jpg"]

# Submit all requests
responses = [
    client.submit(
        endpoint="image/edit/remove_background",
        payload={"image": Image(img).as_bria_api_input}
    )
    for img in images
]

# Wait for all to complete
results = [client.poll(r, timeout=120) for r in responses]
print(f"Processed {len(results)} images")

Async Processing

import asyncio
from bria_client import BriaAsyncClient
from bria_client.toolkit.image import Image

async def process_images():
    async with BriaAsyncClient() as client:
        tasks = [
            client.run(
                endpoint="image/edit/remove_background",
                payload={"image": Image(url).as_bria_api_input}
            )
            for url in ["image1.jpg", "image2.jpg", "image3.jpg"]
        ]
        return await asyncio.gather(*tasks)

results = asyncio.run(process_images())

Error Handling

try:
    response = client.run(endpoint="...", payload={...}, raise_for_status=True)
    print(response.result)
except TimeoutError:
    print("Request timed out")
except Exception as e:
    print(f"Error: {e}")

Development Setup

Prerequisites

  • Python 3.10+
  • uv package manager

Installation

Install development and test dependencies:

uv sync --group dev

Pre-commit Hooks

This project uses pre-commit hooks to ensure code quality. Install them with:

pre-commit install

The following hooks run automatically on each commit:

Hook Description
prettier Formats YAML and JSON files
ruff-format Formats Python code
ruff Lints Python code with auto-fix
pyright Type checking for src/ and tests/
pyright-examples Type checking for examples/ (requires [examples] extra)
uv-lock-check Ensures uv.lock is in sync with pyproject.toml

To run all hooks manually:

pre-commit run --all-files

Contributing

Contributions are welcome! Please follow the Development Setup instructions first, then:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature-name
  3. Make your changes and add tests
  4. Run tests: uv run pytest
  5. Submit a pull request

Guidelines:

  • Add type hints to new code
  • Include tests for new features
  • Follow existing code style
  • Update documentation as needed

Found a bug? Open an issue with:

  • Description of the problem
  • Steps to reproduce
  • Python version and environment

Support

License

MIT License - see LICENSE file for details.


Made by Bria.ai

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bria_client-0.3.0.tar.gz (16.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

bria_client-0.3.0-py3-none-any.whl (23.8 kB view details)

Uploaded Python 3

File details

Details for the file bria_client-0.3.0.tar.gz.

File metadata

  • Download URL: bria_client-0.3.0.tar.gz
  • Upload date:
  • Size: 16.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.24 {"installer":{"name":"uv","version":"0.11.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for bria_client-0.3.0.tar.gz
Algorithm Hash digest
SHA256 446168a2cf53a4e3fe4fa617a5a687b69f68e903d4a6444e5c9e6fbedb8dcfb0
MD5 3c0c927b2f9cc223d8e2408ed52a00c4
BLAKE2b-256 acb886e86c56c5ad13256f4b1d508e98a0549ef2f8db724e557520fd69bcb161

See more details on using hashes here.

File details

Details for the file bria_client-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: bria_client-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 23.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.24 {"installer":{"name":"uv","version":"0.11.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for bria_client-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a5d5cfa06643972f8d770cfed5af639a67acd5a2cee051dfdde15444c89e394b
MD5 2a725b7c8ff8385883537d1ec959779c
BLAKE2b-256 785a91ebbec8997fe9349339fd31b7f5e26bd9a785c30e1380b1ef2c9f4a5309

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page