From e1067e3ac409b9d99843abc22743d4e4ecd66f2a Mon Sep 17 00:00:00 2001 From: Facundo Farias Date: Mon, 16 Nov 2026 16:15:26 +0100 Subject: [PATCH 1/3] feat: add complete video client --- README.md | 26 +- pyproject.toml | 6 +- src/pixelvault/_core.py | 5 +- src/pixelvault/client.py | 6 + src/pixelvault/types.py | 63 ++++ src/pixelvault/videos.py | 746 +++++++++++++++++++++++++++++++++++++++ tests/test_client.py | 212 +++++++++++ uv.lock | 2 +- 8 files changed, 1058 insertions(+), 8 deletions(-) create mode 100644 src/pixelvault/videos.py diff --git a/README.md b/README.md index 25eb106..9b4df80 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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: @@ -55,6 +66,14 @@ 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` | | `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 | @@ -76,8 +95,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 diff --git a/pyproject.toml b/pyproject.toml index 597a82d..d76f0ae 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", diff --git a/src/pixelvault/_core.py b/src/pixelvault/_core.py index 8f23fd6..44dc087 100644 --- a/src/pixelvault/_core.py +++ b/src/pixelvault/_core.py @@ -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 @@ -30,6 +30,8 @@ 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) no_auth: bool = False @@ -45,6 +47,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}" diff --git a/src/pixelvault/client.py b/src/pixelvault/client.py index 56332b5..be8a0b4 100644 --- a/src/pixelvault/client.py +++ b/src/pixelvault/client.py @@ -19,6 +19,7 @@ retryable, ) from .errors import PixelVaultError +from .videos import AsyncVideos, Videos from .types import ( ApiKey, CreatedKey, @@ -53,6 +54,7 @@ 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, ) @@ -60,6 +62,8 @@ def build(self, http: Any, req: Request) -> httpx.Request: def _body(res: httpx.Response) -> Dict[str, Any]: + if not res.content: + return {} body: Dict[str, Any] = res.json() return body @@ -79,6 +83,7 @@ def __init__( self._cfg = _Config(api_key, base_url, max_retries, timeout) self._http = http_client or httpx.Client() self.images = _Images(self) + self.videos = Videos(self) self.usage = _Usage(self) self.keys = _Keys(self) @@ -313,6 +318,7 @@ def __init__( self._cfg = _Config(api_key, base_url, max_retries, timeout) self._http = http_client or httpx.AsyncClient() self.images = _AsyncImages(self) + self.videos = AsyncVideos(self) self.usage = _AsyncUsage(self) self.keys = _AsyncKeys(self) diff --git a/src/pixelvault/types.py b/src/pixelvault/types.py index 9ecc489..0bdfe08 100644 --- a/src/pixelvault/types.py +++ b/src/pixelvault/types.py @@ -126,3 +126,66 @@ class DeviceLoginResult(TypedDict): # Registration and batch responses are passed through as plain dicts. JsonDict = Dict[str, Any] + + +class Video(TypedDict): + id: str + kind: str + url: str + original_url: str + visibility: str + mime_type: str + size: int + width: Optional[int] + height: Optional[int] + duration_seconds: Optional[float] + video_codec: Optional[str] + audio_codec: Optional[str] + has_audio: Optional[bool] + fast_start: Optional[bool] + social_compatible: Optional[bool] + compatibility_warnings: List[Dict[str, Any]] + social_optimization: Dict[str, Any] + enrichment: Dict[str, Any] + filename: str + folder: Optional[str] + collection_id: Optional[str] + metadata: Optional[Dict[str, Any]] + created_at: str + social_ready_url: NotRequired[str] + poster_url: NotRequired[str] + expires_at: NotRequired[str] + temporary: NotRequired[bool] + replayed: NotRequired[bool] + signed_expires: NotRequired[int] + + +class VideoPage(TypedDict): + data: List[Video] + meta: ListMeta + + +class VideoUploadSession(TypedDict): + upload_id: str + asset_id: str + part_size: int + size: int + visibility: str + expires_at: str + asset_expires_at: NotRequired[str] + replayed: NotRequired[bool] + completed: NotRequired[bool] + asset: NotRequired[Video] + + +class VideoUploadedPart(TypedDict): + part_number: int + etag: str + received: int + replayed: NotRequired[bool] + + +class VideoWaitResult(TypedDict): + video: Video + status: str + timed_out: bool diff --git a/src/pixelvault/videos.py b/src/pixelvault/videos.py new file mode 100644 index 0000000..f330027 --- /dev/null +++ b/src/pixelvault/videos.py @@ -0,0 +1,746 @@ +from __future__ import annotations + +import asyncio +import hashlib +import io +import json +import os +import time +from contextlib import contextmanager +from pathlib import Path +from typing import Any, AsyncIterator, BinaryIO, Dict, Iterator, Optional, Tuple, cast +from urllib.parse import quote + +from ._core import FileInput, Request, drop_none +from .types import Video, VideoPage, VideoUploadedPart, VideoUploadSession, VideoWaitResult + + +def _seg(value: str) -> str: + return quote(value, safe="") + + +@contextmanager +def _source(file: FileInput, filename: Optional[str]) -> Iterator[Tuple[BinaryIO, int, str]]: + owned = False + if isinstance(file, (str, os.PathLike)): + path = Path(file) + stream: BinaryIO = path.open("rb") + owned = True + name = filename or path.name + elif isinstance(file, (bytes, bytearray)): + stream = io.BytesIO(file) + owned = True + name = filename or "video.mp4" + else: + stream = file + name = filename or os.path.basename(getattr(file, "name", "") or "") or "video.mp4" + + if not stream.seekable(): + if owned: + stream.close() + raise ValueError("video uploads require a seekable file object") + + start = stream.tell() + stream.seek(0, os.SEEK_END) + size = stream.tell() - start + stream.seek(start) + try: + yield stream, size, name + finally: + if owned: + stream.close() + else: + stream.seek(start) + + +def _digest(stream: BinaryIO) -> str: + start = stream.tell() + digest = hashlib.sha256() + while True: + chunk = stream.read(1024 * 1024) + if not chunk: + break + digest.update(chunk) + stream.seek(start) + return digest.hexdigest() + + +def _lifecycle( + visibility: Optional[str], + sign_expires_in: Optional[int], + expires_in: Optional[int], + folder: Optional[str], + collection_id: Optional[str], + metadata: Optional[Dict[str, Any]], +) -> Dict[str, Any]: + return drop_none( + { + "visibility": visibility, + "sign_expires_in": sign_expires_in, + "expires_in": expires_in, + "folder": folder, + "collection_id": collection_id, + "metadata": metadata, + } + ) + + +def _upload_request( + *, + file: Optional[FileInput] = None, + url: Optional[str] = None, + filename: Optional[str] = None, + visibility: Optional[str] = None, + sign_expires_in: Optional[int] = None, + expires_in: Optional[int] = None, + folder: Optional[str] = None, + collection_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + social_ready: bool = False, + idempotency_key: Optional[str] = None, + sha256: Optional[str] = None, +) -> Request: + if (file is None) == (url is None): + raise ValueError("pass exactly one of `file` or `url`") + + idem_headers = {"Idempotency-Key": idempotency_key} if idempotency_key else {} + lifecycle = _lifecycle( + visibility, sign_expires_in, expires_in, folder, collection_id, metadata + ) + if url is not None: + return Request( + "POST", + "/v1/videos", + json=drop_none( + { + "url": url, + "filename": filename, + "social_ready": social_ready or None, + **lifecycle, + } + ), + headers=idem_headers, + ) + + assert file is not None + with _source(file, filename) as (stream, size, name): + content = stream.read() + digest = sha256 or (hashlib.sha256(content).hexdigest() if idempotency_key else None) + headers = { + "Content-Type": "video/mp4", + "Content-Length": str(size), + "X-PixelVault-Filename": quote(name, safe=""), + **idem_headers, + } + if visibility is not None: + headers["X-PixelVault-Visibility"] = visibility + if sign_expires_in is not None: + headers["X-PixelVault-Sign-Expires-In"] = str(sign_expires_in) + if expires_in is not None: + headers["X-PixelVault-Expires-In"] = str(expires_in) + if folder is not None: + headers["X-PixelVault-Folder"] = folder + if collection_id is not None: + headers["X-PixelVault-Collection-Id"] = collection_id + if metadata is not None: + headers["X-PixelVault-Metadata"] = json.dumps(metadata, separators=(",", ":")) + if social_ready: + headers["X-PixelVault-Social-Ready"] = "true" + if digest is not None: + headers["X-PixelVault-Content-SHA256"] = digest + return Request("POST", "/v1/videos", content=content, headers=headers) + + +def _create_upload_request( + filename: str, + size: int, + *, + sha256: Optional[str] = None, + visibility: Optional[str] = None, + expires_in: Optional[int] = None, + folder: Optional[str] = None, + collection_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + idempotency_key: Optional[str] = None, +) -> Request: + body = { + "filename": filename, + "size": size, + "sha256": sha256, + **_lifecycle(visibility, None, expires_in, folder, collection_id, metadata), + } + return Request( + "POST", + "/v1/videos/uploads", + json=drop_none(body), + headers={"Idempotency-Key": idempotency_key} if idempotency_key else {}, + ) + + +def _upload_part_request( + upload_id: str, part_number: int, content: bytes, sha256: Optional[str] +) -> Request: + headers = { + "Content-Type": "application/octet-stream", + "Content-Length": str(len(content)), + } + if sha256 is not None: + headers["X-PixelVault-Part-SHA256"] = sha256 + return Request( + "PUT", + f"/v1/videos/uploads/{_seg(upload_id)}/parts/{part_number}", + content=content, + headers=headers, + ) + + +def _complete_upload_request( + upload_id: str, social_ready: bool, sign_expires_in: Optional[int] +) -> Request: + headers: Dict[str, str] = {} + if social_ready: + headers["X-PixelVault-Social-Ready"] = "true" + if sign_expires_in is not None: + headers["X-PixelVault-Sign-Expires-In"] = str(sign_expires_in) + return Request( + "POST", f"/v1/videos/uploads/{_seg(upload_id)}/complete", headers=headers + ) + + +def _page(body: Dict[str, Any], page: Optional[int], per_page: Optional[int]) -> VideoPage: + return cast( + VideoPage, + { + "data": body.get("data") or [], + "meta": body.get("meta") + or {"total": 0, "page": page or 1, "per_page": per_page or 0}, + }, + ) + + +def _has_more(result: VideoPage, page: int) -> bool: + per_page = result["meta"].get("per_page") or len(result["data"]) + return bool(result["data"]) and page * per_page < result["meta"].get("total", 0) + + +def _status(video: Video, job: str) -> str: + block = video["enrichment"] if job == "enrichment" else video["social_optimization"] + return str(block.get("status", "not_requested")) + + +class Videos: + def __init__(self, client: Any) -> None: + self._c = client + + def upload( + self, + file: Optional[FileInput] = None, + *, + url: Optional[str] = None, + filename: Optional[str] = None, + visibility: Optional[str] = None, + sign_expires_in: Optional[int] = None, + expires_in: Optional[int] = None, + folder: Optional[str] = None, + collection_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + social_ready: bool = False, + idempotency_key: Optional[str] = None, + sha256: Optional[str] = None, + ) -> Video: + """Upload MP4 bytes/path/file or securely import an HTTPS MP4 URL.""" + req = _upload_request( + file=file, + url=url, + filename=filename, + visibility=visibility, + sign_expires_in=sign_expires_in, + expires_in=expires_in, + folder=folder, + collection_id=collection_id, + metadata=metadata, + social_ready=social_ready, + idempotency_key=idempotency_key, + sha256=sha256, + ) + return cast(Video, self._c._send(req)["data"]) + + def create_upload( + self, + filename: str, + size: int, + *, + sha256: Optional[str] = None, + visibility: Optional[str] = None, + expires_in: Optional[int] = None, + folder: Optional[str] = None, + collection_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + idempotency_key: Optional[str] = None, + ) -> VideoUploadSession: + req = _create_upload_request( + filename, + size, + sha256=sha256, + visibility=visibility, + expires_in=expires_in, + folder=folder, + collection_id=collection_id, + metadata=metadata, + idempotency_key=idempotency_key, + ) + return cast(VideoUploadSession, self._c._send(req)["data"]) + + def upload_part( + self, upload_id: str, part_number: int, content: bytes, *, sha256: Optional[str] = None + ) -> VideoUploadedPart: + return cast( + VideoUploadedPart, + self._c._send(_upload_part_request(upload_id, part_number, content, sha256))["data"], + ) + + def complete_upload( + self, + upload_id: str, + *, + social_ready: bool = False, + sign_expires_in: Optional[int] = None, + ) -> Video: + req = _complete_upload_request(upload_id, social_ready, sign_expires_in) + return cast(Video, self._c._send(req)["data"]) + + def abort_upload(self, upload_id: str) -> None: + self._c._send(Request("DELETE", f"/v1/videos/uploads/{_seg(upload_id)}")) + + def upload_resumable( + self, + file: FileInput, + *, + filename: Optional[str] = None, + sha256: Optional[str] = None, + visibility: Optional[str] = None, + sign_expires_in: Optional[int] = None, + expires_in: Optional[int] = None, + folder: Optional[str] = None, + collection_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + social_ready: bool = False, + idempotency_key: Optional[str] = None, + ) -> Video: + """Replay-safe multipart upload. Reuse the idempotency key to resume.""" + with _source(file, filename) as (stream, size, name): + digest = sha256 or (_digest(stream) if idempotency_key else None) + session = self.create_upload( + name, + size, + sha256=digest, + visibility=visibility, + expires_in=expires_in, + folder=folder, + collection_id=collection_id, + metadata=metadata, + idempotency_key=idempotency_key, + ) + if session.get("completed") and session.get("asset"): + return session["asset"] + part_number = 1 + while True: + part = stream.read(session["part_size"]) + if not part: + break + self.upload_part( + session["upload_id"], + part_number, + part, + sha256=hashlib.sha256(part).hexdigest() if idempotency_key else None, + ) + part_number += 1 + return self.complete_upload( + session["upload_id"], + social_ready=social_ready, + sign_expires_in=sign_expires_in, + ) + + def list( + self, + page: Optional[int] = None, + per_page: Optional[int] = None, + *, + folder: Optional[str] = None, + collection_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + ) -> VideoPage: + params = drop_none( + { + "page": page, + "per_page": per_page, + "folder": folder, + "collection_id": collection_id, + "metadata": json.dumps(metadata, separators=(",", ":")) if metadata else None, + } + ) + return _page(self._c._send(Request("GET", "/v1/videos", params=params)), page, per_page) + + def list_all( + self, + per_page: Optional[int] = None, + *, + folder: Optional[str] = None, + collection_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + ) -> Iterator[Video]: + page = 1 + while True: + result = self.list( + page, per_page, folder=folder, collection_id=collection_id, metadata=metadata + ) + yield from result["data"] + if not _has_more(result, page): + return + page += 1 + + def get(self, video_id: str) -> Video: + return cast(Video, self._c._send(Request("GET", f"/v1/videos/{_seg(video_id)}"))["data"]) + + def update( + self, + video_id: str, + *, + metadata: Any = ..., + folder: Any = ..., + collection_id: Any = ..., + ) -> Video: + body: Dict[str, Any] = {} + if metadata is not ...: + body["metadata"] = metadata + if folder is not ...: + body["folder"] = folder + if collection_id is not ...: + body["collection_id"] = collection_id + return cast( + Video, + self._c._send(Request("PATCH", f"/v1/videos/{_seg(video_id)}", json=body))["data"], + ) + + def delete(self, video_id: str) -> None: + self._c._send(Request("DELETE", f"/v1/videos/{_seg(video_id)}")) + + def sign_url(self, video_id: str, expires_in: Optional[int] = None) -> Video: + req = Request( + "POST", + f"/v1/videos/{_seg(video_id)}/sign-url", + json=drop_none({"expires_in": expires_in}), + ) + return cast(Video, self._c._send(req)["data"]) + + def optimize(self, video_id: str) -> Video: + return self._job(video_id, "optimize") + + def enrich(self, video_id: str) -> Video: + return self._job(video_id, "enrich") + + def analyze(self, video_id: str) -> Video: + return self._job(video_id, "analyze") + + def create_poster(self, video_id: str) -> Video: + return self._job(video_id, "poster") + + def _job(self, video_id: str, operation: str) -> Video: + req = Request("POST", f"/v1/videos/{_seg(video_id)}/{operation}") + return cast(Video, self._c._send(req)["data"]) + + def wait_for_enrichment( + self, + video_id: str, + *, + timeout: float = 600.0, + interval: float = 1.0, + max_interval: float = 5.0, + ) -> VideoWaitResult: + return self._wait(video_id, "enrichment", timeout, interval, max_interval) + + def wait_for_optimization( + self, + video_id: str, + *, + timeout: float = 600.0, + interval: float = 1.0, + max_interval: float = 5.0, + ) -> VideoWaitResult: + return self._wait(video_id, "optimization", timeout, interval, max_interval) + + def _wait( + self, video_id: str, job: str, timeout: float, interval: float, max_interval: float + ) -> VideoWaitResult: + deadline = time.monotonic() + timeout + delay = interval + while True: + video = self.get(video_id) + status = _status(video, job) + if status not in ("pending", "processing"): + return {"video": video, "status": status, "timed_out": False} + remaining = deadline - time.monotonic() + if remaining <= 0: + return {"video": video, "status": status, "timed_out": True} + time.sleep(min(delay, remaining)) + delay = min(delay * 1.5, max_interval) + + +class AsyncVideos: + def __init__(self, client: Any) -> None: + self._c = client + + async def upload( + self, + file: Optional[FileInput] = None, + *, + url: Optional[str] = None, + filename: Optional[str] = None, + visibility: Optional[str] = None, + sign_expires_in: Optional[int] = None, + expires_in: Optional[int] = None, + folder: Optional[str] = None, + collection_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + social_ready: bool = False, + idempotency_key: Optional[str] = None, + sha256: Optional[str] = None, + ) -> Video: + req = await asyncio.to_thread( + _upload_request, + file=file, + url=url, + filename=filename, + visibility=visibility, + sign_expires_in=sign_expires_in, + expires_in=expires_in, + folder=folder, + collection_id=collection_id, + metadata=metadata, + social_ready=social_ready, + idempotency_key=idempotency_key, + sha256=sha256, + ) + return cast(Video, (await self._c._send(req))["data"]) + + async def create_upload( + self, + filename: str, + size: int, + *, + sha256: Optional[str] = None, + visibility: Optional[str] = None, + expires_in: Optional[int] = None, + folder: Optional[str] = None, + collection_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + idempotency_key: Optional[str] = None, + ) -> VideoUploadSession: + req = _create_upload_request( + filename, + size, + sha256=sha256, + visibility=visibility, + expires_in=expires_in, + folder=folder, + collection_id=collection_id, + metadata=metadata, + idempotency_key=idempotency_key, + ) + return cast(VideoUploadSession, (await self._c._send(req))["data"]) + + async def upload_part( + self, upload_id: str, part_number: int, content: bytes, *, sha256: Optional[str] = None + ) -> VideoUploadedPart: + req = _upload_part_request(upload_id, part_number, content, sha256) + return cast(VideoUploadedPart, (await self._c._send(req))["data"]) + + async def complete_upload( + self, + upload_id: str, + *, + social_ready: bool = False, + sign_expires_in: Optional[int] = None, + ) -> Video: + req = _complete_upload_request(upload_id, social_ready, sign_expires_in) + return cast(Video, (await self._c._send(req))["data"]) + + async def abort_upload(self, upload_id: str) -> None: + await self._c._send(Request("DELETE", f"/v1/videos/uploads/{_seg(upload_id)}")) + + async def upload_resumable( + self, + file: FileInput, + *, + filename: Optional[str] = None, + sha256: Optional[str] = None, + visibility: Optional[str] = None, + sign_expires_in: Optional[int] = None, + expires_in: Optional[int] = None, + folder: Optional[str] = None, + collection_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + social_ready: bool = False, + idempotency_key: Optional[str] = None, + ) -> Video: + with _source(file, filename) as (stream, size, name): + digest = sha256 or ( + await asyncio.to_thread(_digest, stream) if idempotency_key else None + ) + session = await self.create_upload( + name, + size, + sha256=digest, + visibility=visibility, + expires_in=expires_in, + folder=folder, + collection_id=collection_id, + metadata=metadata, + idempotency_key=idempotency_key, + ) + if session.get("completed") and session.get("asset"): + return session["asset"] + part_number = 1 + while True: + part = await asyncio.to_thread(stream.read, session["part_size"]) + if not part: + break + await self.upload_part( + session["upload_id"], + part_number, + part, + sha256=hashlib.sha256(part).hexdigest() if idempotency_key else None, + ) + part_number += 1 + return await self.complete_upload( + session["upload_id"], + social_ready=social_ready, + sign_expires_in=sign_expires_in, + ) + + async def list( + self, + page: Optional[int] = None, + per_page: Optional[int] = None, + *, + folder: Optional[str] = None, + collection_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + ) -> VideoPage: + params = drop_none( + { + "page": page, + "per_page": per_page, + "folder": folder, + "collection_id": collection_id, + "metadata": json.dumps(metadata, separators=(",", ":")) if metadata else None, + } + ) + body = await self._c._send(Request("GET", "/v1/videos", params=params)) + return _page(body, page, per_page) + + async def list_all( + self, + per_page: Optional[int] = None, + *, + folder: Optional[str] = None, + collection_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + ) -> AsyncIterator[Video]: + page = 1 + while True: + result = await self.list( + page, per_page, folder=folder, collection_id=collection_id, metadata=metadata + ) + for video in result["data"]: + yield video + if not _has_more(result, page): + return + page += 1 + + async def get(self, video_id: str) -> Video: + body = await self._c._send(Request("GET", f"/v1/videos/{_seg(video_id)}")) + return cast(Video, body["data"]) + + async def update( + self, + video_id: str, + *, + metadata: Any = ..., + folder: Any = ..., + collection_id: Any = ..., + ) -> Video: + body: Dict[str, Any] = {} + if metadata is not ...: + body["metadata"] = metadata + if folder is not ...: + body["folder"] = folder + if collection_id is not ...: + body["collection_id"] = collection_id + result = await self._c._send( + Request("PATCH", f"/v1/videos/{_seg(video_id)}", json=body) + ) + return cast(Video, result["data"]) + + async def delete(self, video_id: str) -> None: + await self._c._send(Request("DELETE", f"/v1/videos/{_seg(video_id)}")) + + async def sign_url(self, video_id: str, expires_in: Optional[int] = None) -> Video: + req = Request( + "POST", + f"/v1/videos/{_seg(video_id)}/sign-url", + json=drop_none({"expires_in": expires_in}), + ) + return cast(Video, (await self._c._send(req))["data"]) + + async def optimize(self, video_id: str) -> Video: + return await self._job(video_id, "optimize") + + async def enrich(self, video_id: str) -> Video: + return await self._job(video_id, "enrich") + + async def analyze(self, video_id: str) -> Video: + return await self._job(video_id, "analyze") + + async def create_poster(self, video_id: str) -> Video: + return await self._job(video_id, "poster") + + async def _job(self, video_id: str, operation: str) -> Video: + req = Request("POST", f"/v1/videos/{_seg(video_id)}/{operation}") + return cast(Video, (await self._c._send(req))["data"]) + + async def wait_for_enrichment( + self, + video_id: str, + *, + timeout: float = 600.0, + interval: float = 1.0, + max_interval: float = 5.0, + ) -> VideoWaitResult: + return await self._wait(video_id, "enrichment", timeout, interval, max_interval) + + async def wait_for_optimization( + self, + video_id: str, + *, + timeout: float = 600.0, + interval: float = 1.0, + max_interval: float = 5.0, + ) -> VideoWaitResult: + return await self._wait(video_id, "optimization", timeout, interval, max_interval) + + async def _wait( + self, video_id: str, job: str, timeout: float, interval: float, max_interval: float + ) -> VideoWaitResult: + deadline = time.monotonic() + timeout + delay = interval + while True: + video = await self.get(video_id) + status = _status(video, job) + if status not in ("pending", "processing"): + return {"video": video, "status": status, "timed_out": False} + remaining = deadline - time.monotonic() + if remaining <= 0: + return {"video": video, "status": status, "timed_out": True} + await asyncio.sleep(min(delay, remaining)) + delay = min(delay * 1.5, max_interval) diff --git a/tests/test_client.py b/tests/test_client.py index a517ecd..a0726d3 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -438,3 +438,215 @@ def handler(req: httpx.Request): await pv.images.list(q="invoice") assert calls[0].url.params["q"] == "invoice" assert (await pv.images.wait_for_description("img_1", interval=0.001))["alt"] == "x" + + +VIDEO = { + "id": "vid_1", + "kind": "video", + "url": "https://img.pixelvault.dev/p/vid_1.mp4", + "original_url": "https://img.pixelvault.dev/p/vid_1.mp4", + "visibility": "public", + "mime_type": "video/mp4", + "size": 3, + "width": 1920, + "height": 1080, + "duration_seconds": 2.0, + "video_codec": "h264", + "audio_codec": "aac", + "has_audio": True, + "fast_start": True, + "social_compatible": True, + "compatibility_warnings": [], + "social_optimization": {"status": "not_requested"}, + "enrichment": {"status": "not_requested"}, + "filename": "clip.mp4", + "folder": None, + "collection_id": None, + "metadata": None, + "created_at": "2026-11-16T00:00:00Z", +} + + +def test_video_upload_bytes_sends_lifecycle_and_idempotency_headers(): + seen = {} + + def handler(req): + seen["request"] = req + return httpx.Response(201, json={"data": VIDEO}) + + video = make(handler).videos.upload( + b"mp4", + filename="hello world.mp4", + visibility="private", + sign_expires_in=300, + expires_in=3600, + folder="demos", + collection_id="col_1", + metadata={"env": "test"}, + social_ready=True, + idempotency_key="retry-1", + sha256="abc123", + ) + req = seen["request"] + assert video["id"] == "vid_1" + assert req.content == b"mp4" + assert req.headers["x-pixelvault-filename"] == "hello%20world.mp4" + assert req.headers["x-pixelvault-visibility"] == "private" + assert req.headers["x-pixelvault-sign-expires-in"] == "300" + assert req.headers["x-pixelvault-expires-in"] == "3600" + assert req.headers["x-pixelvault-folder"] == "demos" + assert req.headers["x-pixelvault-collection-id"] == "col_1" + assert json.loads(req.headers["x-pixelvault-metadata"]) == {"env": "test"} + assert req.headers["idempotency-key"] == "retry-1" + assert req.headers["x-pixelvault-content-sha256"] == "abc123" + + +def test_video_import_is_json_and_replay_safe(): + seen = {} + + def handler(req): + seen["request"] = req + return httpx.Response(201, json={"data": VIDEO}) + + make(handler).videos.upload( + url="https://example.com/clip.mp4", + filename="clip.mp4", + metadata={"source": "demo"}, + idempotency_key="import-1", + ) + req = seen["request"] + assert req.headers["idempotency-key"] == "import-1" + assert json.loads(req.content) == { + "url": "https://example.com/clip.mp4", + "filename": "clip.mp4", + "metadata": {"source": "demo"}, + } + + +def test_video_resumable_upload_and_abort(): + seen = [] + + def handler(req): + seen.append(req) + path = req.url.path + if path == "/v1/videos/uploads": + return httpx.Response( + 201, + json={ + "data": { + "upload_id": "vup_1", + "asset_id": "vid_1", + "part_size": 2, + "size": 3, + "visibility": "private", + "expires_at": "2026-11-16T01:00:00Z", + } + }, + ) + if "/parts/" in path: + number = int(path.rsplit("/", 1)[1]) + return httpx.Response( + 200, + json={"data": {"part_number": number, "etag": str(number), "received": len(req.content)}}, + ) + if path.endswith("/complete"): + return httpx.Response(201, json={"data": VIDEO}) + if req.method == "DELETE": + return httpx.Response(204) + raise AssertionError(path) + + pv = make(handler) + video = pv.videos.upload_resumable( + b"abc", filename="clip.mp4", visibility="private", idempotency_key="resume-1" + ) + pv.videos.abort_upload("vup_old") + assert video["id"] == "vid_1" + assert [request.method for request in seen] == ["POST", "PUT", "PUT", "POST", "DELETE"] + assert seen[0].headers["idempotency-key"] == "resume-1" + assert json.loads(seen[0].content)["sha256"] == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + assert seen[1].headers["x-pixelvault-part-sha256"] + assert seen[2].content == b"c" + + +def test_video_lifecycle_jobs_filters_and_wait_states(): + seen = [] + states = [ + {**VIDEO, "enrichment": {"status": "complete", "job_id": "ven_1"}}, + {**VIDEO, "social_optimization": {"status": "processing", "job_id": "vop_1"}}, + ] + + def handler(req): + seen.append(req) + if req.method == "DELETE": + return httpx.Response(204) + if req.url.path == "/v1/videos" and req.method == "GET": + return httpx.Response( + 200, json={"data": [VIDEO], "meta": {"total": 1, "page": 1, "per_page": 20}} + ) + if req.method == "GET": + return httpx.Response(200, json={"data": states.pop(0)}) + return httpx.Response(200, json={"data": VIDEO}) + + pv = make(handler) + page = pv.videos.list(folder="demos", collection_id="col_1", metadata={"env": "test"}) + pv.videos.update("vid_1", metadata=None, folder="archive", collection_id=None) + pv.videos.sign_url("vid_1", 300) + pv.videos.optimize("vid_1") + pv.videos.enrich("vid_1") + pv.videos.analyze("vid_1") + pv.videos.create_poster("vid_1") + pv.videos.delete("vid_1") + complete = pv.videos.wait_for_enrichment("vid_1", timeout=0) + timed_out = pv.videos.wait_for_optimization("vid_1", timeout=0) + assert page["meta"]["total"] == 1 + assert json.loads(seen[0].url.params["metadata"]) == {"env": "test"} + assert json.loads(seen[1].content) == { + "metadata": None, + "folder": "archive", + "collection_id": None, + } + assert complete["status"] == "complete" and complete["timed_out"] is False + assert timed_out["status"] == "processing" and timed_out["timed_out"] is True + + +@pytest.mark.asyncio +async def test_async_video_import_resumable_and_wait(): + calls = [] + states = [{**VIDEO, "enrichment": {"status": "failed", "job_id": "ven_1"}}] + + def handler(req): + calls.append(req) + if req.url.path == "/v1/videos" and req.method == "POST": + return httpx.Response(201, json={"data": VIDEO}) + if req.url.path == "/v1/videos/uploads": + return httpx.Response( + 201, + json={ + "data": { + "upload_id": "vup_1", + "asset_id": "vid_1", + "part_size": 8, + "size": 3, + "visibility": "public", + "expires_at": "2026-11-16T01:00:00Z", + } + }, + ) + if "/parts/" in req.url.path: + return httpx.Response( + 200, json={"data": {"part_number": 1, "etag": "a", "received": 3}} + ) + if req.url.path.endswith("/complete"): + return httpx.Response(201, json={"data": VIDEO}) + if req.method == "GET": + return httpx.Response(200, json={"data": states.pop(0)}) + raise AssertionError(req.url.path) + + async with amake(handler) as pv: + imported = await pv.videos.upload(url="https://example.com/clip.mp4") + resumed = await pv.videos.upload_resumable( + b"abc", filename="clip.mp4", idempotency_key="async-1" + ) + result = await pv.videos.wait_for_enrichment("vid_1", timeout=0) + assert imported["id"] == resumed["id"] == "vid_1" + assert result["status"] == "failed" and result["timed_out"] is False diff --git a/uv.lock b/uv.lock index ca2f571..ff42c05 100644 --- a/uv.lock +++ b/uv.lock @@ -516,7 +516,7 @@ wheels = [ [[package]] name = "pixelvault" -version = "0.4.0" +version = "0.5.0" source = { editable = "." } dependencies = [ { name = "httpx" }, From ffc7ad30465b0031e1cbd91926aa0062ce996197 Mon Sep 17 00:00:00 2001 From: Facundo Farias Date: Mon, 16 Nov 2026 16:20:55 +0100 Subject: [PATCH 2/3] feat: expose media exports --- README.md | 1 + scripts/check_spec_coverage.py | 14 +++- src/pixelvault/_core.py | 1 + src/pixelvault/client.py | 15 ++-- src/pixelvault/exports.py | 128 +++++++++++++++++++++++++++++++++ src/pixelvault/types.py | 28 ++++++++ tests/test_client.py | 82 +++++++++++++++++++++ 7 files changed, 261 insertions(+), 8 deletions(-) create mode 100644 src/pixelvault/exports.py diff --git a/README.md b/README.md index 9b4df80..8cd4351 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ async with AsyncPixelVault() as pv: | `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 | diff --git a/scripts/check_spec_coverage.py b/scripts/check_spec_coverage.py index d4cb1ff..b70da4e 100644 --- a/scripts/check_spec_coverage.py +++ b/scripts/check_spec_coverage.py @@ -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. @@ -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( diff --git a/src/pixelvault/_core.py b/src/pixelvault/_core.py index 44dc087..cfc7e6d 100644 --- a/src/pixelvault/_core.py +++ b/src/pixelvault/_core.py @@ -32,6 +32,7 @@ class Request: 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 diff --git a/src/pixelvault/client.py b/src/pixelvault/client.py index be8a0b4..8323941 100644 --- a/src/pixelvault/client.py +++ b/src/pixelvault/client.py @@ -20,6 +20,7 @@ ) from .errors import PixelVaultError from .videos import AsyncVideos, Videos +from .exports import AsyncExports, Exports from .types import ( ApiKey, CreatedKey, @@ -61,7 +62,9 @@ def build(self, http: Any, req: Request) -> httpx.Request: 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() @@ -83,6 +86,7 @@ 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) @@ -96,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: @@ -108,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: @@ -318,6 +322,7 @@ 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) @@ -331,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: @@ -343,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: diff --git a/src/pixelvault/exports.py b/src/pixelvault/exports.py new file mode 100644 index 0000000..9a77c2b --- /dev/null +++ b/src/pixelvault/exports.py @@ -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) diff --git a/src/pixelvault/types.py b/src/pixelvault/types.py index 0bdfe08..3b4424c 100644 --- a/src/pixelvault/types.py +++ b/src/pixelvault/types.py @@ -189,3 +189,31 @@ class VideoWaitResult(TypedDict): video: Video status: str timed_out: bool + + +class ExportStart(TypedDict): + job_id: str + status: str + image_count: int + video_count: int + asset_count: int + status_url: str + + +class ExportJob(TypedDict): + id: str + status: str + image_count: int + video_count: int + asset_count: int + processed_count: int + bytes: int + created_at: str + expires_at: str + download_url: NotRequired[str] + error: NotRequired[str] + + +class ExportWaitResult(TypedDict): + job: ExportJob + timed_out: bool diff --git a/tests/test_client.py b/tests/test_client.py index a0726d3..3fa1272 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -650,3 +650,85 @@ def handler(req): result = await pv.videos.wait_for_enrichment("vid_1", timeout=0) assert imported["id"] == resumed["id"] == "vid_1" assert result["status"] == "failed" and result["timed_out"] is False + + +def test_exports_start_wait_and_download_bytes(): + seen = [] + + def handler(req): + seen.append(req) + if req.url.path == "/v1/export": + return httpx.Response( + 202, + json={ + "job_id": "exp_1", + "status": "pending", + "image_count": 2, + "video_count": 1, + "asset_count": 3, + "status_url": "/v1/export-jobs/exp_1", + }, + ) + if req.url.path.endswith("/download"): + return httpx.Response(200, content=b"tar!", headers={"content-type": "application/x-tar"}) + return httpx.Response( + 200, + json={ + "id": "exp_1", + "status": "complete", + "image_count": 2, + "video_count": 1, + "asset_count": 3, + "processed_count": 3, + "bytes": 4, + "created_at": "2026-11-16T00:00:00Z", + "expires_at": "2026-11-17T00:00:00Z", + "download_url": "/v1/export-jobs/exp_1/download", + }, + ) + + pv = make(handler) + started = pv.exports.start(project_id="proj_1") + waited = pv.exports.wait(started["job_id"], project_id="proj_1", timeout=0) + archive = pv.exports.download(started["job_id"], project_id="proj_1") + assert started["video_count"] == 1 + assert waited["job"]["status"] == "complete" and waited["timed_out"] is False + assert archive == b"tar!" + assert all(req.url.params["project_id"] == "proj_1" for req in seen) + assert seen[2].headers["accept"] == "application/x-tar" + + +@pytest.mark.asyncio +async def test_async_exports_timeout_is_local(): + def handler(req): + if req.url.path == "/v1/export": + return httpx.Response( + 202, + json={ + "job_id": "exp_1", + "status": "pending", + "image_count": 0, + "video_count": 1, + "asset_count": 1, + "status_url": "/v1/export-jobs/exp_1", + }, + ) + return httpx.Response( + 200, + json={ + "id": "exp_1", + "status": "processing", + "image_count": 0, + "video_count": 1, + "asset_count": 1, + "processed_count": 0, + "bytes": 0, + "created_at": "2026-11-16T00:00:00Z", + "expires_at": "2026-11-17T00:00:00Z", + }, + ) + + async with amake(handler) as pv: + started = await pv.exports.start() + result = await pv.exports.wait(started["job_id"], timeout=0) + assert result["job"]["status"] == "processing" and result["timed_out"] is True From a8c4eca33a97d5a8664863dfe402b009c56cda57 Mon Sep 17 00:00:00 2001 From: Facundo Farias Date: Mon, 16 Nov 2026 16:23:45 +0100 Subject: [PATCH 3/3] fix: match video signing response --- src/pixelvault/types.py | 8 ++++++++ src/pixelvault/videos.py | 21 ++++++++++++++++----- tests/test_client.py | 14 +++++++++++++- 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/src/pixelvault/types.py b/src/pixelvault/types.py index 3b4424c..a9904cd 100644 --- a/src/pixelvault/types.py +++ b/src/pixelvault/types.py @@ -217,3 +217,11 @@ class ExportJob(TypedDict): class ExportWaitResult(TypedDict): job: ExportJob timed_out: bool + + +class VideoSignedUrls(TypedDict): + url: str + enrichment: Dict[str, Any] + expires: int + poster_url: NotRequired[str] + social_url: NotRequired[str] diff --git a/src/pixelvault/videos.py b/src/pixelvault/videos.py index f330027..b4d967d 100644 --- a/src/pixelvault/videos.py +++ b/src/pixelvault/videos.py @@ -12,7 +12,14 @@ from urllib.parse import quote from ._core import FileInput, Request, drop_none -from .types import Video, VideoPage, VideoUploadedPart, VideoUploadSession, VideoWaitResult +from .types import ( + Video, + VideoPage, + VideoSignedUrls, + VideoUploadedPart, + VideoUploadSession, + VideoWaitResult, +) def _seg(value: str) -> str: @@ -425,13 +432,15 @@ def update( def delete(self, video_id: str) -> None: self._c._send(Request("DELETE", f"/v1/videos/{_seg(video_id)}")) - def sign_url(self, video_id: str, expires_in: Optional[int] = None) -> Video: + def sign_url( + self, video_id: str, expires_in: Optional[int] = None + ) -> VideoSignedUrls: req = Request( "POST", f"/v1/videos/{_seg(video_id)}/sign-url", json=drop_none({"expires_in": expires_in}), ) - return cast(Video, self._c._send(req)["data"]) + return cast(VideoSignedUrls, self._c._send(req)["data"]) def optimize(self, video_id: str) -> Video: return self._job(video_id, "optimize") @@ -685,13 +694,15 @@ async def update( async def delete(self, video_id: str) -> None: await self._c._send(Request("DELETE", f"/v1/videos/{_seg(video_id)}")) - async def sign_url(self, video_id: str, expires_in: Optional[int] = None) -> Video: + async def sign_url( + self, video_id: str, expires_in: Optional[int] = None + ) -> VideoSignedUrls: req = Request( "POST", f"/v1/videos/{_seg(video_id)}/sign-url", json=drop_none({"expires_in": expires_in}), ) - return cast(Video, (await self._c._send(req))["data"]) + return cast(VideoSignedUrls, (await self._c._send(req))["data"]) async def optimize(self, video_id: str) -> Video: return await self._job(video_id, "optimize") diff --git a/tests/test_client.py b/tests/test_client.py index 3fa1272..238ad78 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -583,6 +583,17 @@ def handler(req): return httpx.Response( 200, json={"data": [VIDEO], "meta": {"total": 1, "page": 1, "per_page": 20}} ) + if req.url.path.endswith("/sign-url"): + return httpx.Response( + 200, + json={ + "data": { + "url": "https://signed.example/video.mp4?sig=x", + "enrichment": VIDEO["enrichment"], + "expires": 123, + } + }, + ) if req.method == "GET": return httpx.Response(200, json={"data": states.pop(0)}) return httpx.Response(200, json={"data": VIDEO}) @@ -590,7 +601,7 @@ def handler(req): pv = make(handler) page = pv.videos.list(folder="demos", collection_id="col_1", metadata={"env": "test"}) pv.videos.update("vid_1", metadata=None, folder="archive", collection_id=None) - pv.videos.sign_url("vid_1", 300) + signed = pv.videos.sign_url("vid_1", 300) pv.videos.optimize("vid_1") pv.videos.enrich("vid_1") pv.videos.analyze("vid_1") @@ -605,6 +616,7 @@ def handler(req): "folder": "archive", "collection_id": None, } + assert signed["url"] == "https://signed.example/video.mp4?sig=x" assert complete["status"] == "complete" and complete["timed_out"] is False assert timed_out["status"] == "processing" and timed_out["timed_out"] is True