Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 24 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# pixelvault

Official Python SDK for [PixelVault](https://pixelvault.dev), agent-first image hosting.
Official Python SDK for [PixelVault](https://pixelvault.dev), agent-first media hosting.
Sync and asyncio clients on top of `httpx`. Python 3.9+.

```bash
Expand Down Expand Up @@ -30,6 +30,17 @@ Generate an image from a prompt and host it in one call (spends monthly credits,
image = pv.images.generate("flat vector hero, a robot at a laptop, no text")
print(image["url"]) # https://img.pixelvault.dev/...
print(image["generation"]) # {'model': 'flux-1-schnell', 'credits_charged': 1, 'credits_remaining': 9}

video = pv.videos.upload(
"demo.mp4",
idempotency_key="upload-attempt-42",
visibility="private",
)
pv.videos.enrich(video["id"])
result = pv.videos.wait_for_enrichment(video["id"], timeout=600)
print(result["video"]["original_url"])
print(result["video"]["enrichment"].get("transcript"))
print(result["video"]["enrichment"].get("storyboard"))
```

Asyncio:
Expand All @@ -55,6 +66,15 @@ async with AsyncPixelVault() as pv:
| `images.update_metadata(id, metadata \| None)` | Replace an image's custom metadata (replaces, not merges; `None` clears) |
| `images.get(id)` / `images.delete(id)` | Fetch / delete one image |
| `images.sign_url(id, expires_in=)` | Signed URL for a private image |
| `videos.upload(file \| url=, ...)` | Upload or securely import an MP4 with visibility, TTL, metadata, folder, collection, idempotency and optional social optimization |
| `videos.upload_resumable(file, ...)` | Replay-safe multipart upload; rerun with the same idempotency key to resume |
| `videos.create_upload(...)` / `upload_part(...)` / `complete_upload(...)` / `abort_upload(...)` | Manual resumable-upload lifecycle |
| `videos.get(id)` / `list(...)` / `list_all(...)` / `delete(id)` | Video discovery and lifecycle |
| `videos.update(id, metadata=, folder=, collection_id=)` | Replace metadata and organization fields; pass `None` to clear |
| `videos.sign_url(id, expires_in=)` | Fresh private original, poster and available artifact URLs |
| `videos.optimize(id)` / `enrich(id)` | Start asynchronous optimization or transcript/storyboard enrichment |
| `videos.wait_for_optimization(id, ...)` / `wait_for_enrichment(id, ...)` | Bounded polling with backoff; returns video, terminal/current status and `timed_out` |
| `exports.start()` / `wait(job_id)` / `download(job_id)` | Owner-authenticated tar export of non-expired images, videos, available derivatives and `manifest.json` relationships |
| `usage.get()` | Plan, usage, limits and what is left this month (including generation credits) |
| `keys.list()` / `keys.create(label=, environment=)` / `keys.revoke(id)` | Manage your API keys (secret keys only) |
| `register(email)` | Create an account, returns a first key once |
Expand All @@ -76,8 +96,9 @@ except PixelVaultError as err:
```

The client retries `429` (honoring `Retry-After` up to 30 seconds) and, for `GET`/`DELETE` only, `5xx` and
network errors. Uploads and `images.generate` are never retried after a `5xx` or a network error, so a lost response cannot create a duplicate image or spend credits twice.
Tune with `max_retries` (default 2) and `timeout` (seconds, default 60).
network errors. Uploads, job creation and `images.generate` are not retried after a `5xx` or network error.
Use an `idempotency_key` for replay-safe video direct/import/resumable uploads. A wait timing out locally does
not cancel the server job. Tune with `max_retries` (default 2) and `timeout` (seconds, default 60).

## License

Expand Down
6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ build-backend = "hatchling.build"

[project]
name = "pixelvault"
version = "0.4.0"
description = "Official Python SDK for PixelVault, agent-first image hosting"
version = "0.5.0"
description = "Official Python SDK for PixelVault, agent-first media hosting"
readme = "README.md"
license = "MIT"
license-files = ["LICENSE"]
requires-python = ">=3.9"
authors = [{ name = "PixelVault" }]
keywords = ["pixelvault", "image-hosting", "sdk", "upload", "agent"]
keywords = ["pixelvault", "media-hosting", "image-hosting", "video-hosting", "sdk", "upload", "agent"]
classifiers = [
"Programming Language :: Python :: 3",
"Typing :: Typed",
Expand Down
14 changes: 11 additions & 3 deletions scripts/check_spec_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@
import urllib.request

COVERED = {
"upload_image", "generate_image", "batch_upload", "list_images", "get_image", "update_image_metadata", "delete_image",
"sign_image_url", "get_usage", "list_keys", "create_key", "revoke_key",
"upload_image", "generate_image", "batch_upload", "list_images", "get_image", "update_image_metadata",
"delete_image", "sign_image_url", "get_usage", "list_keys", "create_key", "revoke_key",
"register_account", "device_login_start", "device_login_complete",
"list_videos", "upload_video", "get_video", "delete_video", "update_video", "optimize_video",
"enrich_video", "analyze_video", "generate_video_poster", "sign_video_url",
"create_video_upload", "upload_video_part", "complete_video_upload", "abort_video_upload",
"start_export", "get_export_job", "download_export",
}
# Not wrapped on purpose: dashboard-session endpoints, the public playground,
# health, and surfaces the SDK does not cover yet.
Expand All @@ -23,7 +27,11 @@
# Billing: a person pays or cancels, so it is a dashboard/portal flow, not an SDK call.
"start_checkout", "open_billing_portal",
"list_collections", "get_collection", "close_collection",
"start_export", "get_export_job", "download_export",
# Advanced image, webhook, and anonymous-playground surfaces are intentionally separate.
"describe_image", "edit_image", "list_image_tags", "playground_video_upload",
"list_webhooks", "create_webhook", "update_webhook", "delete_webhook",
"rotate_webhook_secret", "list_webhook_deliveries",

}

req = urllib.request.Request(
Expand Down
6 changes: 5 additions & 1 deletion src/pixelvault/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

from .errors import PixelVaultError

__version__ = "0.4.0"
__version__ = "0.5.0"

DEFAULT_BASE_URL = "https://api.pixelvault.dev"
MAX_BACKOFF = 30.0
Expand All @@ -30,6 +30,9 @@ class Request:
json: Optional[Dict[str, Any]] = None
files: Optional[Dict[str, Tuple[str, Any, str]]] = None
data: Optional[Dict[str, str]] = None
content: Optional[bytes] = None
headers: Dict[str, str] = field(default_factory=dict)
response_bytes: bool = False
no_auth: bool = False


Expand All @@ -45,6 +48,7 @@ def headers_for(api_key: Optional[str], req: Request) -> Dict[str, str]:
headers = {
"Accept": "application/json",
"X-PixelVault-Client": f"sdk-python/{__version__}",
**req.headers,
}
if api_key and not req.no_auth:
headers["Authorization"] = f"Bearer {api_key}"
Expand Down
21 changes: 16 additions & 5 deletions src/pixelvault/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
retryable,
)
from .errors import PixelVaultError
from .videos import AsyncVideos, Videos
from .exports import AsyncExports, Exports
from .types import (
ApiKey,
CreatedKey,
Expand Down Expand Up @@ -53,13 +55,18 @@ def build(self, http: Any, req: Request) -> httpx.Request:
json=req.json,
files=req.files,
data=req.data,
content=req.content,
headers=headers_for(self.api_key, req),
timeout=self.timeout,
)
return built


def _body(res: httpx.Response) -> Dict[str, Any]:
def _body(res: httpx.Response, response_bytes: bool = False) -> Any:
if response_bytes:
return res.content
if not res.content:
return {}
body: Dict[str, Any] = res.json()
return body

Expand All @@ -79,6 +86,8 @@ def __init__(
self._cfg = _Config(api_key, base_url, max_retries, timeout)
self._http = http_client or httpx.Client()
self.images = _Images(self)
self.exports = Exports(self)
self.videos = Videos(self)
self.usage = _Usage(self)
self.keys = _Keys(self)

Expand All @@ -91,7 +100,7 @@ def __exit__(self, *exc: Any) -> None:
def close(self) -> None:
self._http.close()

def _send(self, req: Request) -> Dict[str, Any]:
def _send(self, req: Request) -> Any:
attempt = 0
while True:
try:
Expand All @@ -103,7 +112,7 @@ def _send(self, req: Request) -> Dict[str, Any]:
continue
raise network_error(exc) from exc
if res.is_success:
return _body(res)
return _body(res, req.response_bytes)
if attempt < self._cfg.max_retries and retryable(req.method, res.status_code):
wait = backoff(attempt, res)
if wait is not None:
Expand Down Expand Up @@ -313,6 +322,8 @@ def __init__(
self._cfg = _Config(api_key, base_url, max_retries, timeout)
self._http = http_client or httpx.AsyncClient()
self.images = _AsyncImages(self)
self.exports = AsyncExports(self)
self.videos = AsyncVideos(self)
self.usage = _AsyncUsage(self)
self.keys = _AsyncKeys(self)

Expand All @@ -325,7 +336,7 @@ async def __aexit__(self, *exc: Any) -> None:
async def close(self) -> None:
await self._http.aclose()

async def _send(self, req: Request) -> Dict[str, Any]:
async def _send(self, req: Request) -> Any:
attempt = 0
while True:
try:
Expand All @@ -337,7 +348,7 @@ async def _send(self, req: Request) -> Dict[str, Any]:
continue
raise network_error(exc) from exc
if res.is_success:
return _body(res)
return _body(res, req.response_bytes)
if attempt < self._cfg.max_retries and retryable(req.method, res.status_code):
wait = backoff(attempt, res)
if wait is not None:
Expand Down
128 changes: 128 additions & 0 deletions src/pixelvault/exports.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
from __future__ import annotations

import asyncio
import time
from typing import Any, Optional, cast
from urllib.parse import quote

from ._core import Request, drop_none
from .types import ExportJob, ExportStart, ExportWaitResult


def _seg(value: str) -> str:
return quote(value, safe="")


class Exports:
def __init__(self, client: Any) -> None:
self._c = client

def start(self, project_id: Optional[str] = None) -> ExportStart:
"""Start an owner-authenticated media export with a relationship manifest."""
return cast(
ExportStart,
self._c._send(
Request("POST", "/v1/export", params=drop_none({"project_id": project_id}))
),
)

def get(self, job_id: str, project_id: Optional[str] = None) -> ExportJob:
return cast(
ExportJob,
self._c._send(
Request(
"GET",
f"/v1/export-jobs/{_seg(job_id)}",
params=drop_none({"project_id": project_id}),
)
),
)

def download(self, job_id: str, project_id: Optional[str] = None) -> bytes:
return cast(
bytes,
self._c._send(
Request(
"GET",
f"/v1/export-jobs/{_seg(job_id)}/download",
params=drop_none({"project_id": project_id}),
headers={"Accept": "application/x-tar"},
response_bytes=True,
)
),
)

def wait(
self,
job_id: str,
*,
project_id: Optional[str] = None,
timeout: float = 600.0,
interval: float = 1.0,
max_interval: float = 5.0,
) -> ExportWaitResult:
deadline = time.monotonic() + timeout
delay = interval
while True:
job = self.get(job_id, project_id)
if job["status"] not in ("pending", "processing"):
return {"job": job, "timed_out": False}
remaining = deadline - time.monotonic()
if remaining <= 0:
return {"job": job, "timed_out": True}
time.sleep(min(delay, remaining))
delay = min(delay * 1.5, max_interval)


class AsyncExports:
def __init__(self, client: Any) -> None:
self._c = client

async def start(self, project_id: Optional[str] = None) -> ExportStart:
result = await self._c._send(
Request("POST", "/v1/export", params=drop_none({"project_id": project_id}))
)
return cast(ExportStart, result)

async def get(self, job_id: str, project_id: Optional[str] = None) -> ExportJob:
result = await self._c._send(
Request(
"GET",
f"/v1/export-jobs/{_seg(job_id)}",
params=drop_none({"project_id": project_id}),
)
)
return cast(ExportJob, result)

async def download(self, job_id: str, project_id: Optional[str] = None) -> bytes:
result = await self._c._send(
Request(
"GET",
f"/v1/export-jobs/{_seg(job_id)}/download",
params=drop_none({"project_id": project_id}),
headers={"Accept": "application/x-tar"},
response_bytes=True,
)
)
return cast(bytes, result)

async def wait(
self,
job_id: str,
*,
project_id: Optional[str] = None,
timeout: float = 600.0,
interval: float = 1.0,
max_interval: float = 5.0,
) -> ExportWaitResult:
deadline = time.monotonic() + timeout
delay = interval
while True:
job = await self.get(job_id, project_id)
if job["status"] not in ("pending", "processing"):
return {"job": job, "timed_out": False}
remaining = deadline - time.monotonic()
if remaining <= 0:
return {"job": job, "timed_out": True}
await asyncio.sleep(min(delay, remaining))
delay = min(delay * 1.5, max_interval)
Loading
Loading