Metadata-Version: 2.4
Name: videopiper
Version: 0.2.0
Summary: Official Python SDK for the Video Piper API: upload, import, edit and stream videos, with webhook verification.
Author: PodWorks3D LLC
License: MIT
Project-URL: Homepage, https://videopiper.com/docs/
Keywords: video,api,sdk,video-api,transcoding,hls,webhooks,live-streaming
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# videopiper

The official Python SDK for the [Video Piper](https://videopiper.com/) API: upload or import videos, cut and join them, stream live, and check webhooks. Python 3.9 or newer, no dependencies (it uses the standard library), type hints included.

```sh
pip install videopiper
```

Keep your API key on your server. To let a browser upload, record or edit, make a short-lived token with the SDK and give the page that (see [Tokens for browsers](#tokens-for-browsers)).

## Quickstart

Upload a file, wait for it to process, and get the download link:

```python
from videopiper import VideoPiper

client = VideoPiper()  # reads VIDEO_PIPER_API_KEY

upload = client.videos.upload_file("lesson.mp4", title="Lesson 1")
video = client.videos.wait_until_done(upload["videoId"])

if video["status"] == "SUCCEEDED":
    print(video["downloadUrl"])  # an MP4 link, valid for 15 minutes
else:
    print("Processing ended with", video["status"])
```

`upload_file` creates the video, then for each part asks for its upload URL just before sending that part (the URLs expire after 15 minutes), sends the bytes with no `Authorization` header, and completes the upload. Any file size works; parts go one at a time and only one part is held in memory.

## Setup

```python
client = VideoPiper(
    api_key="vpk_...",                        # default: the VIDEO_PIPER_API_KEY environment variable
    base_url="https://api.videopiper.dev/v1",  # default: VIDEO_PIPER_API_URL, then this
    timeout=60,                                # seconds, per request
    max_retries=3,                             # see Retries
)
```

Other options: `upload_timeout` (per part, default 10 minutes), `retry_base_delay`, `max_retry_delay`, `requests_per_second` (default 5, the API's limit per key; 0 turns it off) and `transport` (an object with `send(method, url, headers, body, timeout)`, to use instead of `urllib`).

Arguments are Python names (`file_name`, `max_height`) and are sent with the API's camelCase names. Objects inside a request (`trim`, `redactions`, `clips`, `metadata`) are sent exactly as the [API docs](https://videopiper.com/docs/) show them. Responses are plain dicts with the API's keys; `videopiper.types` has `TypedDict`s for the main ones.

## Videos

```python
# Upload from disk, from bytes, or from a file-like object
client.videos.upload_file("lesson.mp4", max_height=720, captions=True, on_progress=print)
client.videos.upload_bytes(data, "clip.mp4", metadata={"lessonId": "123"})
client.videos.upload_stream(stream, size_bytes, "recording.webm")

# Have the API download a public HTTPS URL
video = client.videos.import_url("https://example.com/tutorial.mp4", max_height=1080)

# Status, and the links once it has finished
status = client.videos.get(video["videoId"])  # playbackUrl, streamUrl, downloadUrl, posterUrl
done = client.videos.wait_until_done(video["videoId"], timeout=600, on_status=lambda s: print(s["status"]))

# Lists: one page, or every video
page = client.videos.list(limit=25, metadata={"lessonId": "123"})
for item in client.videos.list_all(limit=100):
    print(item["videoId"], item.get("outcome"))

client.videos.update(video_id, title="New title", metadata={"archived": None})  # None clears
client.videos.reprocess(video_id, max_height=2160, trim={"start": 30})           # a new video from the same upload
client.videos.cancel(video_id)                                                   # stop processing
client.videos.delete(video_id)
```

`wait_until_done` checks the status with a growing pause (3 s up to 15 s) until the video reaches a final status and returns it; `FAILED`, `TIMED_OUT` and `ABORTED` are returned, not raised, so look at `["status"]`. It raises `WaitTimeoutError` after `timeout` seconds (default 30 minutes). In production prefer [webhooks](#webhooks) to polling.

The steps behind `upload_file` are public too, for streaming uploads and other special cases: `create`, `get_part_urls`, `complete`, `abort` and `heartbeat`.

Also on `client.videos`: `list_thumbnails`, `choose_thumbnail`, `get_chapters`, `set_chapters`, `delete_chapters` and `set_embed`.

## Edits

Make a new video from clips of finished videos: trim, stitch and splice.

```python
edit = client.edits.create(
    [
        {"videoId": intro_id, "end": 60},
        {"videoId": lesson_id, "start": 90, "transition": {"type": "fade", "seconds": 0.75}},
    ],
    file_name="Lesson 1 (final)",
)
```

**Music or a voice-over:** add `audio` (1 to 4 files of your own, any format FFmpeg reads, up to 200 MB each). The SDK creates the edit with each file's name and size, uploads the files in parts and calls `complete`, so the answer is the same `{"videoId": ..., "status": "SUBMITTED", "clips": ...}` as above. Each track can start `at` a time on the edit, use only `start`–`end` of the file, have a `volume` (0–2), `fadeIn`/`fadeOut` (seconds), `loop` to the end of the video, and `duck` (drop while the clips have sound). A clip's own `volume` (0 mutes it) makes room for a voice-over. The track settings use the API's names, like `clips` do.

```python
# A quiet song under the whole video, ducked under the speech, fading out at the end
client.edits.create(
    [{"videoId": intro_id}, {"videoId": lesson_id, "transition": {"type": "fade"}}],
    audio=[{"file": "song.mp3", "volume": 0.4, "loop": True, "duck": True, "fadeOut": 3}],
)

# A narration over muted clips, from bytes you hold (then fileName is required)
client.edits.create(
    [{"videoId": demo_id, "volume": 0}],
    audio=[{"file": narration_bytes, "fileName": "narration.wav", "at": 2, "end": 90, "fadeIn": 0.5}],
    on_progress=lambda p: print(p["fileName"], p["partNumber"], "/", p["partCount"]),
)
```

`file` is a path or `bytes`. Without `audio`, `edits.create` is one request and nothing changes.

## Dry runs and idempotency

`dry_run=True` checks a request without creating or starting anything (it doesn't count toward your daily limit) and returns `{"valid": True, "dryRun": True, ...}`; an edit also reports its length. It works on `videos.create`, `import_url`, `complete`, `reprocess`, `edits.create` and `live_streams.create`.

```python
check = client.edits.create(clips, dry_run=True)
print(check["durationSeconds"])
```

An `idempotency_key` makes a retry safe: the same key with the same request returns the first response again (kept 24 hours) instead of creating a second video.

```python
client.videos.import_url(url, idempotency_key=f"import-{lesson_id}")
client.videos.upload_file(path, idempotency_key=f"upload-{lesson_id}")  # complete uses "<key>:complete"
```

## Tokens for browsers

```python
upload = client.upload_tokens.create(max_seconds=600, metadata={"userId": "u_1"})
# <video-piper-recorder upload-token="{upload['uploadToken']}">
edit = client.edit_tokens.create([a, b], max_seconds=300)
thumb = client.thumbnail_tokens.create(video_id)
```

These go with the web components in [`@videopiper/elements`](https://www.npmjs.com/package/@videopiper/elements).

## Usage and account

```python
usage = client.usage.get("2026-10")  # processing, storage and delivery against the plan
account = client.account.get()
```

## Live streams (Pro and Scale)

```python
stream = client.live_streams.create(title="Product demo", record=True, max_duration_minutes=60)
print(stream["ingest"]["rtmpsUrl"], stream["ingest"]["streamKey"])  # for OBS: give the key only to the broadcaster
print(stream["watch"]["url"])                                       # for viewers
client.live_streams.end(stream["liveStreamId"])                     # the recording becomes a normal video
```

Also `get`, `list`, `list_all`, `update`, `get_ingest` and `delete`.

## Recording links

Send someone a link to record a video into your account: they open it, record their screen, camera or both in the browser (or
pick a file), and the video lands in your videos with their name and email in its metadata. No account or app on their side.

```python
link = client.recording_links.create(title="Record a short intro", message="Two minutes about yourself.",
                                     modes=["screen+camera", "camera"], max_seconds=120)
print(link["url"])                    # send this; one recording by default (max_recordings=5, or None for no limit)
client.recording_links.delete(link["recordingLinkId"])   # stops it at once; recordings already made stay
```

Also `get` and `list`. Recording in the browser is Pro and Scale; a link that offers only `file` works on every plan.

## Webhooks

Set the endpoint, and keep the signing secret it returns:

```python
config = client.webhooks.set("https://example.com/hooks/video-piper", events=["video.ready", "video.failed"])
# config["secret"] is "whsec_..."
```

Check every delivery with `verify_webhook` on the **raw** body (before JSON parsing). It returns the parsed event, or raises `WebhookVerificationError` if a header is missing, no signature matches (it accepts several, separated by spaces), or the timestamp is more than 5 minutes off (change it with `tolerance_seconds`).

```python
from flask import Flask, request
from videopiper import WebhookVerificationError, verify_webhook

app = Flask(__name__)

@app.post("/hooks/video-piper")
def video_piper_hook():
    try:
        event = verify_webhook(WEBHOOK_SECRET, request.get_data(), request.headers)
    except WebhookVerificationError:
        return "", 401
    if event["type"] == "video.ready":
        print("ready", event["data"]["videoId"])
    return "", 204
```

Deliveries are at-least-once: deduplicate on `event["id"]` (the `webhook-id` header). Also on `client.webhooks`: `get`, `delete`, `rotate_secret`, `test` and `deliveries`.

## Errors

Every failed call raises `VideoPiperError`:

```python
from videopiper import VideoPiperError

try:
    client.videos.upload_file("lesson.mp4")
except VideoPiperError as error:
    print(error.status, error.code, error.message, error.request_id)
    if error.code == "PLAN_LIMIT_REACHED":
        ...  # out of Free minutes
    for problem in error.details or []:  # INVALID_REQUEST lists every problem
        print(problem["field"], problem["message"])
    raise
```

Program against `code` (`PLAN_LIMIT_REACHED`, `DAILY_LIMIT`, `RATE_LIMITED`, `NOT_FOUND`, ...), not the message. Quote `request_id` when asking for help. A request that got no answer raises `VideoPiperConnectionError` (`status` 0, `code` `CONNECTION_ERROR`); `wait_until_done` running out of time raises `WaitTimeoutError`. All three are `VideoPiperError`s.

## Retries and rate limits

Failed requests are sent again, up to `max_retries` times with exponential backoff and jitter, when it is safe: network errors, `RATE_LIMITED` (429) and 500, 502, 503 or 504, on `GET`, `PUT`, `PATCH` and `DELETE`, on the idempotent `POST`s (part URLs, `complete`, `cancel`, `abort`) and on any `POST` that carries an `idempotency_key`. Daily, quota and plan limits are not retried. A `Retry-After` header is honoured (a wait longer than `max_retry_delay`, 60 s by default, raises instead).

The client sends at most 5 requests a second (the API's limit per key); lower or raise it with `requests_per_second`.

## Test mode

A test key (`vp_test_...`, made in the app under Account, API keys, Create test key) works the same way and is free: it only sees test videos, which are one MP4 of at most 60 seconds and 480p, marked TEST, and deleted after 24 hours. Use it in tests and CI. A test key can't read the account or change the webhook, and `usage.get` is always empty for it.

```python
client = VideoPiper(os.environ["VIDEO_PIPER_TEST_KEY"])
```

Test webhook events carry `livemode: false`.

## License

MIT. Docs: <https://videopiper.com/docs/>.
