> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vidnavigator.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> Install and use the official VidNavigator Python SDK (v2.4.0) to transcribe, analyze, extract, and search video content.

The official Python client for the VidNavigator API. Every response is a typed Pydantic model (v1 and v2 both work), and long-running work such as speech-to-text, extraction, tweet analysis and TikTok scraping runs as background jobs, so **media of any length works with a single call**. It ships a synchronous client and an [asyncio client](#async-client) with the same methods.

[![PyPI version](https://img.shields.io/pypi/v/vidnavigator)](https://pypi.org/project/vidnavigator/)
[![Python versions](https://img.shields.io/pypi/pyversions/vidnavigator)](https://pypi.org/project/vidnavigator/)
[![License](https://img.shields.io/pypi/l/vidnavigator)](https://github.com/vidnavigator/vidnavigator-python/blob/main/LICENSE)

> [card] [PyPI package](https://pypi.org/project/vidnavigator/)
>
> `vidnavigator` 2.4.0 on the Python Package Index.

> [card] [GitHub repository](https://github.com/vidnavigator/vidnavigator-python)
>
> Source code, issues and changelog.

> [!NOTE]
>
> This page documents **version 2.4.0**. Coming from 1.x? See [Upgrading from 1.x](#upgrading-from-1x).

## Installation

```bash pip
pip install vidnavigator==2.4.0
```

```bash poetry
poetry add vidnavigator@2.4.0
```

```bash uv
uv add vidnavigator==2.4.0
```

For the [asyncio client](#async-client), install the `async` extra, which adds [`httpx`](https://pypi.org/project/httpx/) >= 0.23:

```bash pip
pip install "vidnavigator[async]==2.4.0"
```

```bash poetry
poetry add "vidnavigator[async]==2.4.0"
```

```bash uv
uv add "vidnavigator[async]==2.4.0"
```

**Requirements:** Python 3.8+, [`requests`](https://pypi.org/project/requests/) >= 2.31 and [`pydantic`](https://pypi.org/project/pydantic/) >= 1.10 (installed automatically).

## Authentication

Get your API key in the [Developer Dashboard](https://vidnavigator.com/studio/api).

```python
from vidnavigator import VidNavigatorClient

# Reads the VIDNAVIGATOR_API_KEY environment variable
client = VidNavigatorClient()

# Or pass the key explicitly
client = VidNavigatorClient(api_key="YOUR_API_KEY")
```

### Configuration

```python
client = VidNavigatorClient(
    api_key="YOUR_API_KEY",       # or set VIDNAVIGATOR_API_KEY
    base_url="https://...",       # override the API base URL
    timeout=60,                   # per HTTP request, in seconds (default: 30)
    session=my_requests_session,  # bring your own requests.Session
)
```

The client's `timeout` applies to each HTTP request. It is separate from the `timeout` argument of job methods such as `transcribe_video(timeout=...)`, which limits how long to wait for a whole [background job](#background-jobs).

Use the client as a context manager to close its HTTP session automatically. One client can be reused for any number of calls; if you use threads, create one client per thread. For asyncio code, use [`AsyncVidNavigatorClient`](#async-client).

```python
with VidNavigatorClient() as client:
    resp = client.get_transcript(video_url="https://www.youtube.com/watch?v=dQw4w9WgXcQ")
    print(resp.data.transcript)
```

## Quick start

```python
from vidnavigator import VidNavigatorClient

client = VidNavigatorClient()

# 1. Captions of a YouTube video
resp = client.get_transcript(video_url="https://www.youtube.com/watch?v=dQw4w9WgXcQ", transcript_text=True)
print(resp.data.transcript)

# 2. Speech-to-text for a video without captions (any length)
resp = client.transcribe_video(video_url="https://www.instagram.com/reel/C86ZvEaqRmo/", transcript_text=True)
print(resp.data.transcript)

# 3. Structured data from a video
resp = client.extract_video_data(
    video_url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    schema={"mood": {"type": "String", "description": "Overall mood in one word"}},
)
print(resp.data)  # {"mood": "upbeat"}

# 4. What a video shows, scene by scene, next to what it says
resp = client.watch_video(video_url="https://www.youtube.com/watch?v=dQw4w9WgXcQ")
for scene in resp.data.scenes:
    print(scene.start, scene.end, scene.description, scene.on_screen_text)
```

## Which method should I use?

| I want to...                                                         | Use                                                                                 | Returns                   |
| -------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------- |
| Get the captions of a video (fast, cheap)                            | `get_transcript`                                                                    | immediately               |
| Transcribe audio when there are no captions (Instagram, TikTok, ...) | `transcribe_video`                                                                  | when the job finishes     |
| See what a video shows, scene by scene, with its transcript          | `watch_video`                                                                       | when the job finishes     |
| Summarize a video or ask a question about it                         | `analyze_video`                                                                     | immediately               |
| Pull specific fields out of a video into a `dict`                    | `extract_video_data`                                                                | when the job finishes     |
| Analyze the claim made in a tweet                                    | `get_tweet_statement`                                                               | when the job finishes     |
| List a TikTok profile's videos                                       | `scrape_tiktok_profile`                                                             | when the job finishes     |
| Search TikTok by keyword                                             | `search_tiktok`                                                                     | when the job finishes     |
| Find TikTok LIVE rooms broadcasting now, with their stream URLs      | `search_tiktok_live`                                                                | when the job finishes     |
| Find YouTube videos about a topic                                    | `search_youtube`                                                                    | immediately               |
| Work with your own audio/video files                                 | `upload_file`, then `get_file`, `analyze_file`, `extract_file_data`, `search_files` | immediately               |
| Process **many** videos at once                                      | the `submit_*` version of a job method                                              | a job handle, right away  |
| Call the API from asyncio code (FastAPI, aiohttp, bots, agents)      | [`AsyncVidNavigatorClient`](#async-client)                                          | the same results, awaited |

"When the job finishes" methods run as [background jobs](#background-jobs): they block until the result is ready, however long the media is. Each one also has a `submit_*` version that returns immediately.

### Supported platforms

| Platform        |        Transcript (captions)        | Transcribe (speech-to-text) | Watch (scenes) |                   Carousel                  |
| --------------- | :---------------------------------: | :-------------------------: | :------------: | :-----------------------------------------: |
| YouTube         |                 Yes                 |              -              |       Yes      |                      -                      |
| Instagram Reels |                  -                  |             Yes             |       Yes      |                     Yes                     |
| Instagram Posts |                  -                  |             Yes             |       Yes      |              Yes (`all_videos`)             |
| TikTok          |                 Yes                 |             Yes             |       Yes      |                      -                      |
| X / Twitter     |                 Yes                 |             Yes             |       Yes      |                      -                      |
| Vimeo           |                 Yes                 |             Yes             |       Yes      |                      -                      |
| Facebook        |                 Yes                 |             Yes             |       Yes      |                      -                      |
| Dailymotion     |                 Yes                 |             Yes             |       Yes      |                      -                      |
| Loom            |                 Yes                 |             Yes             |       Yes      |                      -                      |
| Snapchat        | Yes, when Snapchat has a transcript |             Yes             |       Yes      | Yes (highlights: `img_index`, `all_videos`) |
| Uploaded files  |                 Yes                 |             Yes             |        -       |                      -                      |

**Watch** = what the video shows, scene by scene, next to its transcript, via [`watch_video`](#watch).

---

## Transcripts

### Captions from any platform

`get_transcript` handles every supported platform; the API detects the platform from the URL. Instagram has no captions, so use [`transcribe_video`](#speech-to-text) for it.

```python
resp = client.get_transcript(video_url="https://www.youtube.com/watch?v=dQw4w9WgXcQ")

print(resp.data.video_info.title)
# "Rick Astley - Never Gonna Give You Up (Official Music Video)"

for segment in resp.data.transcript:
    print(f"[{segment.start:.1f}s] {segment.text}")
# [0.0s] We're no strangers to love
# [3.2s] You know the rules and so do I
```

Pass `transcript_text=True` to get one plain string instead of segments:

```python
resp = client.get_transcript(video_url="https://www.youtube.com/watch?v=dQw4w9WgXcQ", transcript_text=True)
print(resp.data.transcript)
# "We're no strangers to love. You know the rules and so do I..."
```

| Parameter              | Type   | Description                                                                                        |
| ---------------------- | ------ | -------------------------------------------------------------------------------------------------- |
| `video_url`            | `str`  | URL of the video                                                                                   |
| `language`             | `str`  | ISO 639-1 language code (e.g. `"en"`, `"fr"`)                                                      |
| `transcript_text`      | `bool` | Return the transcript as a single string instead of segments                                       |
| `metadata_only`        | `bool` | Return only video metadata, no transcript                                                          |
| `fallback_to_metadata` | `bool` | Return metadata with an empty transcript instead of raising `NotFoundError` when no captions exist |
| `include_usage`        | `bool` | Attach a per-call [`usage`](#per-call-usage) block                                                 |

> [!NOTE]
>
> `get_youtube_transcript` still works as a deprecated alias for `get_transcript`.

### Speech-to-text

For videos without captions, `transcribe_video` runs speech-to-text as a [background job](#background-jobs): it submits the video, waits for the transcript, and returns it. Long videos work exactly like short ones.

```python
resp = client.transcribe_video(video_url="https://www.instagram.com/reel/C86ZvEaqRmo/")

print(resp.data.video_info.title)
for segment in resp.data.transcript:
    print(f"[{segment.start:.1f}s] {segment.text}")
```

| Parameter         | Type    | Description                                                                                                                |
| ----------------- | ------- | -------------------------------------------------------------------------------------------------------------------------- |
| `video_url`       | `str`   | URL of the video (`?img_index=N` selects one video of an Instagram carousel)                                               |
| `transcript_text` | `bool`  | Return the transcript as a single string instead of segments                                                               |
| `all_videos`      | `bool`  | Carousel posts only: transcribe every video. Returns `carousel_info` and `videos` instead of `video_info` and `transcript` |
| `include_usage`   | `bool`  | Attach a `usage` block to the result                                                                                       |
| `webhook_url`     | `str`   | Optional; see [Webhooks](#webhooks)                                                                                        |
| `timeout`         | `float` | Seconds to wait for the job (default `3600`; `None` waits indefinitely)                                                    |

### Instagram carousels

Pick one video with `?img_index=N` in the URL, or transcribe all of them:

```python
resp = client.transcribe_video(
    video_url="https://www.instagram.com/p/ABC123/",
    all_videos=True,
)

print(resp.data.carousel_info.video_count)
for video in resp.data.videos:
    print(f"Video {video.index} ({video.status}): {video.transcript}")
```

### Captions first, speech-to-text as a fallback

Captions are faster and cheaper than speech-to-text, so a common pattern is to try them first:

```python
from vidnavigator import BadRequestError, NotFoundError

def best_transcript(url):
    try:
        return client.get_transcript(video_url=url, transcript_text=True).data.transcript
    except (NotFoundError, BadRequestError):  # no captions, or a platform without captions
        return client.transcribe_video(video_url=url, transcript_text=True).data.transcript
```

---

## Watch

> [!NOTE]
>
> New in **2.4.0**.

`watch_video` reads what a video **shows**, next to what it says. The result holds the transcript and a list of scenes: for each one, when it starts and ends, a description of the picture, and the text readable on screen. It works with every platform `get_transcript` and `transcribe_video` support, and runs as a [background job](#background-jobs).

```python
resp = client.watch_video(video_url="https://www.tiktok.com/@nasa/video/7300000000000000000")

for scene in resp.data.scenes:
    print(f"[{scene.start:.0f}s - {scene.end:.0f}s] {scene.description}")
    if scene.on_screen_text:
        print(f"    on screen: {scene.on_screen_text}")
# [4s - 12s] A presenter stands in front of a world map and points at Europe.
#     on screen: BREAKING NEWS

for segment in resp.data.transcript or []:
    print(f"[{segment.start:.1f}s] {segment.text}")

print(resp.data.frames_analyzed)  # number of frames that were analyzed
```

The transcript comes from the platform's captions when it has them, and from speech-to-text otherwise. A video without speech is not an error: `transcript` is empty, `transcript_error` says why, and the scenes are returned. The same goes for a YouTube video without captions.

```python
resp = client.watch_video(video_url=url)
if resp.data.transcript_error:
    print(resp.data.transcript_error.error)  # e.g. "transcript_not_available"
print(len(resp.data.scenes), "scenes")
```

| Parameter            | Type    | Description                                                                                                                                                                                                                                                  |
| -------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `video_url`          | `str`   | URL of the video (`?img_index=N` selects one video of an Instagram carousel or a Snapchat highlight)                                                                                                                                                         |
| `detail`             | `str`   | How closely the picture is followed: `"low"`, `"auto"` (the default) or `"high"`. The number of frames depends on the video at every level: few on a fixed shot, many on a fast-cut clip. A higher level analyzes more frames when the picture changes often |
| `include_transcript` | `bool`  | Default `True`. `False` returns the scenes only (`transcript` is `None`)                                                                                                                                                                                     |
| `transcript_text`    | `bool`  | Return the transcript as a single string instead of segments                                                                                                                                                                                                 |
| `include_usage`      | `bool`  | Attach a `usage` block to the result; the frames are its `frame_analysis` charge                                                                                                                                                                             |
| `webhook_url`        | `str`   | Optional; see [Webhooks](#webhooks)                                                                                                                                                                                                                          |
| `timeout`            | `float` | Seconds to wait for the job (default `3600`; `None` waits indefinitely). See [Timeouts](#timeouts-never-lose-the-task_id)                                                                                                                                    |

To start it without waiting, use the handle, as for any background job:

```python
job = client.watch.submit(video_url=url, detail="high")   # or client.submit_watch_video(...)
print(job.task_id)

resp = job.result(include_usage=True)                     # waits if needed
print(resp.usage.charge_for("frame_analysis").quantity)   # the frames, as the frame_analysis charge

job = client.watch.resume(saved_task_id)                  # the same handle, later
job = client.resume_job("watch", saved_task_id)           # the same, by job type
```

Errors worth handling: `NotFoundError` with `error_code == "frames_not_available"` (a live stream, or a clip of a few seconds, has no picture to read) and `BadRequestError` with `error_code == "video_too_long"` (videos longer than 2 hours are not accepted, except on YouTube).

See the [Watching Videos guide](https://docs.vidnavigator.com/guides/watching-videos.md) and the [Watch endpoint](https://docs.vidnavigator.com/api-reference/endpoint/watch.md).

---

## AI analysis

Get a summary, the people, places and key subjects, and a direct answer to a natural-language question. `query` is optional.

```python Online video
resp = client.analyze_video(
    video_url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    query="What is the main message of this song?",
)

analysis = resp.data.transcript_analysis

print(analysis.summary)
# "The song is a declaration of unwavering commitment and loyalty..."

print(analysis.query_answer.answer)
# "The main message is a promise to never give up on someone..."

# people, places and key_subjects are lists of plain dicts
for person in analysis.people or []:
    print(person)   # {"name": "Rick Astley", "context": "Singer and performer of the song"}

for subject in analysis.key_subjects or []:
    print(subject)  # {"name": "commitment", "description": "...", "importance": "high"}
```

```python Uploaded file
resp = client.analyze_file(
    file_id="your_file_id",
    query="What are the key action items from this meeting?",
)
print(resp.data.transcript_analysis.summary)
```

Pass `transcript_text=True` to also receive the transcript as one string. See the [Analyzing Videos guide](https://docs.vidnavigator.com/guides/analyzing-videos.md) for billing details.

---

## Structured extraction

Describe the fields you want and the API fills them in from the transcript. See the [Data Extraction guide](https://docs.vidnavigator.com/guides/data-extraction.md) for schema design tips.

### From an online video

```python
resp = client.extract_video_data(
    video_url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    schema={
        "mood": {"type": "String", "description": "Overall mood of the video in one word"},
        "main_topics": {
            "type": "Array",
            "description": "List of main topics discussed",
            "items": {"type": "String", "description": "A topic"},
        },
        "has_spoken_lyrics": {
            "type": "Boolean",
            "description": "Whether the video contains spoken or sung lyrics",
        },
    },
    what_to_extract="Focus on the tone and content of the lyrics.",
)

print(resp.data)
# {"mood": "upbeat", "main_topics": ["love", "commitment"], "has_spoken_lyrics": True}

print(resp.video_info.title, resp.video_info.duration)
# "Rick Astley - Never Gonna Give You Up (Official Music Video)" 212.0
```

`extract_video_data` runs as a [background job](#background-jobs). With `transcribe=True` (the default), a video without captions is transcribed first, however long it is. Set `transcribe=False` to never run speech-to-text.

The extracted fields are in `resp.data`, and the video's metadata (a `VideoInfo`) in `resp.video_info`, so you don't need a separate `get_transcript(metadata_only=True)` call.

> [!NOTE]
>
> `video_info` on extraction results requires **2.1.0**. In 2.0.0 it is always `None`.

### Schema format

Each field needs a `type` and a `description`. A schema can have at most 10 top-level fields and 3 levels of nesting.

| `type`                                   | Extra keys                         | Example value                        |
| ---------------------------------------- | ---------------------------------- | ------------------------------------ |
| `String`, `Number`, `Integer`, `Boolean` | --                                 | `"upbeat"`, `4.5`, `3`, `True`       |
| `Enum`                                   | `enum`: the allowed values         | `"positive"`                         |
| `Array`                                  | `items`: the schema of one element | `["love", "commitment"]`             |
| `Object`                                 | `properties`: the sub-fields       | `{"name": "Rick", "role": "singer"}` |

```python
schema = {
    "sentiment": {
        "type": "Enum",
        "description": "Overall sentiment of the video",
        "enum": ["positive", "negative", "neutral"],
    },
    "speaker": {
        "type": "Object",
        "description": "The main speaker or singer",
        "properties": {
            "name": {"type": "String", "description": "Their name"},
            "role": {"type": "String", "description": "Their role in the video"},
        },
    },
    "key_takeaway": {"type": "String", "description": "The single most important takeaway"},
}
```

An invalid schema raises `BadRequestError` with `error_code == "invalid_schema"` **before** anything is transcribed or billed.

### From a schema file

Keep schemas in JSON or YAML files and pass `schema_file` instead of `schema`:

```yaml meeting-schema.yaml
action_items:
  type: Array
  description: Action items mentioned in the meeting
  items:
    type: String
    description: One action item
decisions_made:
  type: Array
  description: Key decisions that were agreed upon
  items:
    type: String
    description: One decision
```

```python Python
resp = client.extract_video_data(video_url="...", schema_file="./meeting-schema.yaml")
```

### From an uploaded file

```python
resp = client.extract_file_data(
    file_id="your_file_id",
    schema_file="./meeting-schema.yaml",  # or schema={...}
    what_to_extract="Extract action items and deadlines.",
)
print(resp.data)
```

### Token usage

```python
resp = client.extract_video_data(
    video_url="...",
    schema={"summary": {"type": "String", "description": "One-line summary"}},
    include_usage=True,
)
tokens = resp.usage.analysis_tokens
print(f"LLM tokens: {tokens.total_tokens} (prompt {tokens.prompt_tokens}, completion {tokens.completion_tokens})")
```

---

## Tweet claim analysis

```python
resp = client.get_tweet_statement(tweet_id="1585841080431321088")

print(resp.data.final_statement)      # the core claim, in the author's voice
print(resp.data.detailed_analysis)    # claim, context, evidence and stance
print(resp.data.claim_type, resp.data.intent, resp.data.tone)
print(resp.data.topics, resp.data.entities)
print(resp.data.tweet_media_summary)  # summary of attached video/images, if any
```

Videos attached to the tweet (or to the tweet it quotes) are transcribed in full, so this runs as a [background job](#background-jobs) too. `claim_type`, `intent`, `tone`, `emotion` and `authority` are based on the original tweet text only. See the [Tweet Claim Analysis guide](https://docs.vidnavigator.com/guides/tweet-claim-analysis.md).

---

## Background jobs

Speech-to-text, watch, extraction, tweet analysis and TikTok operations run as **background jobs** on VidNavigator's servers. The SDK always uses the [async endpoints](https://docs.vidnavigator.com/guides/async-jobs.md), so media of any length works without special handling.

Each job operation comes in two shapes, which take the same parameters:

| Operation                     | Blocking: wait and return the result | Non-blocking: return a `Job` handle |
| ----------------------------- | ------------------------------------ | ----------------------------------- |
| Speech-to-text                | `transcribe_video(...)`              | `submit_transcribe_video(...)`      |
| Watch (scenes and transcript) | `watch_video(...)`                   | `submit_watch_video(...)`           |
| Structured extraction         | `extract_video_data(...)`            | `submit_extract_video_data(...)`    |
| Tweet claim analysis          | `get_tweet_statement(...)`           | `submit_tweet_statement(...)`       |
| TikTok profile scrape         | `scrape_tiktok_profile(...)`         | `submit_tiktok_profile_scrape(...)` |
| TikTok keyword search         | `search_tiktok(...)`                 | `submit_tiktok_search(...)`         |
| TikTok LIVE search            | `search_tiktok_live(...)`            | `submit_tiktok_live_search(...)`    |

With a handle, `include_usage`, `timeout` and (for TikTok) `limit` are passed to `job.result()` instead.

### Operation objects

> [!NOTE]
>
> New in **2.2.0**.

Each operation is also an object, as in the JavaScript SDK. Call it to wait for the result, use `.submit(...)` for a handle, and `.resume(task_id)` to rebuild one later:

```python
result = client.tiktok_search(query="grève", country="fr")      # waits, every result
job = client.tiktok_search.submit(query="grève", country="fr")  # returns a Job right away
job = client.tiktok_search.resume(saved_task_id)                # same handle, later
```

The objects are `client.transcribe`, `client.watch`, `client.extract_video`, `client.tweet_statement`, `client.tiktok_profile`, `client.tiktok_search` and `client.tiktok_live_search`, with the same parameters as the methods above. The async client has the same ones (`await client.tiktok_search(...)`).

### Submit now, collect later

```python
job = client.submit_transcribe_video(video_url="https://www.instagram.com/reel/C86ZvEaqRmo/")
print(job.task_id)   # "550e8400-e29b-41d4-a716-446655440000" -- save it
print(job.status())  # "processing"

# ... do other work ...

resp = job.result()  # waits if needed, then returns the same TranscriptResponse as transcribe_video
```

> [accordion] Job members
>
> | Member                                    | Description                                                                                                                        |
> | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
> | `task_id`                                 | The job's id. Keep it so you can [resume](#timeouts-never-lose-the-task_id) later                                                  |
> | `job_type`                                | `"transcribe"`, `"watch"`, `"extract_video"`, `"tweet_statement"`, `"tiktok_profile"`, `"tiktok_search"` or `"tiktok_live_search"` |
> | `status()`                                | Polls once and returns `"processing"`, `"completed"` or `"failed"`                                                                 |
> | `done()`                                  | Polls once; `True` when the job is `completed` or `failed`                                                                         |
> | `result(...)`                             | Waits, then returns the same object as the blocking method; raises if the job failed                                               |
> | `wait(...)`                               | Waits, then returns the raw poll response (job metadata, the `request` you sent, `webhook` delivery status)                        |
> | `refresh()`                               | Polls once and returns the raw poll response                                                                                       |
> | `webhook_url`, `check_status_url`, `data` | What the API returned when the job was submitted                                                                                   |

> [accordion] result() and wait() arguments
>
> | Argument           | Default | Description                                                                  |
> | ------------------ | ------- | ---------------------------------------------------------------------------- |
> | `timeout`          | `3600`  | Seconds to wait; `None` waits indefinitely                                   |
> | `include_usage`    | `False` | Attach the job's `usage` block (available once completed)                    |
> | `poll_interval`    | `3`     | Seconds between polls                                                        |
> | `fast_start`       | `True`  | Poll every second for the first 10 seconds, so short clips return quickly    |
> | `limit`, `cursor`  | --      | TikTok jobs only: which page of results to return                            |
> | `raise_on_failure` | `True`  | `wait()` only: pass `False` to get a failed job back instead of an exception |

> [accordion] Result types
>
> | Operation                             | Returned by the blocking method and by `result()`                                                                                                                     |
> | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
> | Transcribe                            | `TranscriptResponse` (`data.video_info`, `data.transcript`), or `TranscribeAllVideosResponse` with `all_videos=True`                                                  |
> | Watch                                 | `WatchResponse` (`data.video_info`, `data.transcript`, `data.scenes`, `data.frames_analyzed`)                                                                         |
> | Extract                               | `ExtractionApiResponse` (`data` is a `dict` matching your schema, `video_info` the video's metadata)                                                                  |
> | Tweet                                 | `TweetStatementResponse` (`data.final_statement`, `data.detailed_analysis`, ...)                                                                                      |
> | TikTok profile / search / LIVE search | `TikTokProfileResponse` / `TikTokSearchResponse` / `TikTokLiveSearchResponse`, with every video / result / room (all pages merged), or one page when you pass `limit` |

Polling is free and not rate-limited. A job's result stays readable for **1 hour after it finishes**, and reading it does not consume it.

### Timeouts: never lose the `task_id`

Blocking calls and `result()` wait up to `timeout` seconds (default one hour), then raise `JobTimeoutError`. The job **keeps running on the server**, and the error carries the `task_id` and a ready-to-use handle:

```python
from vidnavigator import JobTimeoutError

try:
    resp = client.transcribe_video(video_url=url, timeout=600)
except JobTimeoutError as exc:
    print("Still running:", exc.task_id)
    resp = exc.job.result()  # keep waiting on the same job
```

Later, or from another process, rebuild the handle from a saved id with `resume_job`:

```python
job = client.resume_job("transcribe", task_id)
if job.done():
    resp = job.result()
```

### Failures

A failed job raises the exception that matches its `error.http_status`, so the same `except` clauses work for direct calls and jobs. A failed job has all its charges reverted.

```python
from vidnavigator import BadRequestError, PaymentRequiredError, VidNavigatorError

try:
    resp = client.transcribe_video(video_url=url)
except PaymentRequiredError:
    print("Out of transcription credit")
except BadRequestError as exc:
    print(exc.error_code, exc)  # e.g. "unsupported_platform"
except VidNavigatorError as exc:
    print("Job failed:", exc)
```

To inspect a failure without an exception, use `job.wait(raise_on_failure=False)` and read `resp.data.error`.

Some errors happen **at submit time**, before a job exists:

| Exception                | Status | When                                                                                                                 |
| ------------------------ | ------ | -------------------------------------------------------------------------------------------------------------------- |
| `PaymentRequiredError`   | 402    | Not enough credit to start the job. Can also be raised by `result()` if the job runs out of credit while running     |
| `TooManyActiveJobsError` | 429    | Too many jobs already running for your account; retry once some finish ([recipe](#stay-under-the-running-job-limit)) |
| `BadRequestError`        | 400    | Invalid parameters, an invalid extraction schema, or a non-public `webhook_url`                                      |

---

## Recipes

### Process many videos at once

Submit every job first, then collect the results. All the jobs run **at the same time on the server**:

```python
urls = [
    "https://www.tiktok.com/@a/video/1",
    "https://www.tiktok.com/@b/video/2",
    "https://www.tiktok.com/@c/video/3",
]

jobs = [client.submit_transcribe_video(video_url=url, transcript_text=True) for url in urls]
results = [job.result() for job in jobs]

for url, resp in zip(urls, results):
    print(url, resp.data.transcript[:80])
```

With jobs that take 60 s, 40 s and 90 s, the batch takes about **90 s** (the slowest job). Calling the blocking `transcribe_video` in a loop would take 190 s.

To let one job fail without stopping the batch, catch errors per job:

```python
from vidnavigator import VidNavigatorError

for url, job in zip(urls, jobs):
    try:
        print(url, job.result().data.transcript[:80])
    except VidNavigatorError as exc:
        print(url, "failed:", exc.error_code, exc)
```

### Handle results as soon as they finish

```python
import time

pending = list(jobs)
while pending:
    for job in list(pending):
        if job.done():            # one free poll
            handle(job.result())  # already finished: returns immediately
            pending.remove(job)
    time.sleep(3)
```

### Stay under the running-job limit

Past your account's limit, a submit raises `TooManyActiveJobsError` and no task is created. For large batches, keep a bounded number of jobs running:

```python
import time
from vidnavigator import TooManyActiveJobsError, VidNavigatorError

MAX_RUNNING = 5
queue = list(urls)
running = []  # (url, job) pairs
results, errors = {}, {}

while queue or running:
    # Fill free slots
    while queue and len(running) < MAX_RUNNING:
        try:
            running.append((queue[0], client.submit_transcribe_video(video_url=queue[0])))
            queue.pop(0)
        except TooManyActiveJobsError:
            break  # the account is at its limit; retry after some jobs finish

    # Collect finished jobs
    for url, job in list(running):
        if job.done():
            try:
                results[url] = job.result()
            except VidNavigatorError as exc:
                errors[url] = exc
            running.remove((url, job))

    time.sleep(3)
```

### Survive a restart

Save the `task_id` when you submit, and resume with `resume_job`:

```python
import json

job = client.submit_extract_video_data(video_url=url, schema=schema)
with open("jobs.json", "w") as f:
    json.dump({"job_type": job.job_type, "task_id": job.task_id}, f)

# ... after a restart ...
with open("jobs.json") as f:
    saved = json.load(f)
resp = client.resume_job(saved["job_type"], saved["task_id"]).result()
```

### Transcribe every video of a TikTok profile

```python
profile = client.scrape_tiktok_profile(profile_url="https://www.tiktok.com/@tiktok", max_posts=20, limit=20)

jobs = [
    client.submit_transcribe_video(video_url=video.url, transcript_text=True)
    for video in profile.data.videos or []
    if video.url
]
for job in jobs:
    print(job.result().data.transcript[:80])
```

---

## Async client

`AsyncVidNavigatorClient` has the same methods, arguments and return types as `VidNavigatorClient`, as coroutines. Use it from asyncio code such as FastAPI, aiohttp, Discord bots or agent frameworks: while a job runs, waiting uses `asyncio.sleep`, so the event loop keeps serving other work.

> [!NOTE]
>
> New in **2.1.0**. Install the `async` extra: `pip install "vidnavigator[async]==2.1.0"`.

```python
import asyncio
from vidnavigator import AsyncVidNavigatorClient

async def main():
    async with AsyncVidNavigatorClient() as client:  # reads VIDNAVIGATOR_API_KEY
        resp = await client.transcribe_video(video_url="https://www.instagram.com/reel/C86ZvEaqRmo/")
        print(resp.data.transcript)

asyncio.run(main())
```

### Many jobs at once

`asyncio.gather` runs every call concurrently. Each job is submitted immediately and polled in the background of the same event loop:

```python
async with AsyncVidNavigatorClient() as client:
    results = await asyncio.gather(
        *(client.transcribe_video(video_url=url, transcript_text=True) for url in urls),
        return_exceptions=True,  # one failed job doesn't cancel the others
    )

for url, resp in zip(urls, results):
    if isinstance(resp, Exception):
        print(url, "failed:", resp)
    else:
        print(url, resp.data.transcript[:80])
```

To cap how many jobs run at once (see [the running-job limit](#stay-under-the-running-job-limit)), wrap each call in an `asyncio.Semaphore`:

```python
limit = asyncio.Semaphore(5)

async def transcribe(url):
    async with limit:
        return await client.transcribe_video(video_url=url)

results = await asyncio.gather(*(transcribe(url) for url in urls))
```

### Async job handles

`submit_*` methods return an `AsyncJob`. It has the same members as [`Job`](#submit-now-collect-later), with `status()`, `done()`, `refresh()`, `wait()` and `result()` as coroutines.

```python
job = await client.submit_extract_video_data(video_url=url, schema=schema)
print(job.task_id)

if not await job.done():
    ...  # do other work
resp = await job.result()
print(resp.data, resp.video_info.title)
```

Timeouts work as in the sync client: `JobTimeoutError` carries the `task_id` and an `AsyncJob` handle, so `await exc.job.result()` resumes waiting. `client.resume_job(job_type, task_id)` rebuilds a handle later; it is a plain method, not a coroutine.

### In a FastAPI app

Create one client for the app's lifetime and share it across requests:

```python
from contextlib import asynccontextmanager
from fastapi import FastAPI
from vidnavigator import AsyncVidNavigatorClient

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.vidnavigator = AsyncVidNavigatorClient()
    yield
    await app.state.vidnavigator.aclose()

app = FastAPI(lifespan=lifespan)

@app.post("/jobs")
async def start_transcription(video_url: str):
    job = await app.state.vidnavigator.submit_transcribe_video(video_url=video_url)
    return {"task_id": job.task_id}

@app.get("/jobs/{task_id}")
async def job_status(task_id: str):
    job = app.state.vidnavigator.resume_job("transcribe", task_id)
    resp = await job.refresh()
    return {"status": resp.data.task_status}
```

### Async configuration

```python
import httpx

client = AsyncVidNavigatorClient(
    api_key="YOUR_API_KEY",   # or set VIDNAVIGATOR_API_KEY
    base_url="https://...",   # override the API base URL
    timeout=60,               # per HTTP request, in seconds (default: 30)
    http_client=httpx.AsyncClient(limits=httpx.Limits(max_connections=20)),  # optional; you close it yourself
)
```

- Close the client with `await client.aclose()`, or use `async with`. A client you pass as `http_client` is not closed for you.
- The [webhook helpers](#webhooks) are plain functions and work unchanged in async code.
- The deprecated aliases `get_youtube_transcript` and `search_videos` are not available on the async client. Use `get_transcript` and `search_youtube`.

---

## Webhooks

Every job method, blocking or `submit_*`, accepts a `webhook_url`. **Webhooks are optional:** polling always works, whether or not a webhook is configured.

```python
job = client.submit_extract_video_data(
    video_url="https://www.tiktok.com/@user/video/1234567890",
    schema={"summary": {"type": "String", "description": "One-line summary"}},
    webhook_url="https://example.com/hooks/vidnavigator",
)
print(job.webhook_url)  # which webhook the job will call, or None
```

- The URL must be a publicly reachable `https` address; private, loopback and link-local hosts raise `BadRequestError`.
- A default webhook can be set in [Studio → API](https://vidnavigator.com/studio/api). A per-request `webhook_url` overrides it, and `webhook_url=""` opts a single job out.

### Receive and verify deliveries

`construct_webhook_event` checks the HMAC-SHA256 signature and the timestamp, then returns a typed `WebhookEvent`. Always pass the **raw** request body:

```python
from flask import Flask, request
from vidnavigator import VidNavigatorClient, WebhookSignatureError, construct_webhook_event

app = Flask(__name__)
client = VidNavigatorClient()
WEBHOOK_SECRET = "your_signing_secret"

@app.post("/hooks/vidnavigator")
def vidnavigator_webhook():
    try:
        event = construct_webhook_event(
            request.get_data(),
            request.headers.get("X-VidNavigator-Signature"),
            WEBHOOK_SECRET,
        )
    except WebhookSignatureError:
        return "invalid signature", 400

    delivery_id = request.headers.get("X-VidNavigator-Delivery")  # stable across retries
    if already_processed(delivery_id):
        return "", 200

    if event.type == "transcribe.completed":
        # The job handle gives the typed result, even when the event omits it
        resp = client.resume_job("transcribe", event.data.task_id).result()
        save_transcript(event.data.task_id, resp.data.transcript)
    elif event.type.endswith(".failed"):
        print(event.data.task_id, event.data.error.error, event.data.error.message)

    return "", 200
```

- `event.data.result` also holds the result as a plain `dict`, unless it was over 256 KB (`data.result_truncated` is `True`).
- For `extract_video.completed` events, `event.data.video_info` holds the video's metadata as a plain `dict`. It is sent even when the result was truncated.
- For TikTok events, `event.data.result` is only a summary (`stats`, `download_url_available`); read the videos with `client.resume_job("tiktok_search", event.data.task_id).result()`.
- Deliveries more than 5 minutes old are rejected; change the window with `tolerance_seconds=` (or `None` to skip the check).
- `verify_webhook_signature(body, header, secret)` verifies without parsing and raises the same `WebhookSignatureError`.

Event types are `transcribe.*`, `watch.*`, `extract_video.*`, `tweet_statement.*`, `tiktok_profile.*`, `tiktok_search.*` and `tiktok_live_search.*`, each `.completed` or `.failed`. See [Webhooks](https://docs.vidnavigator.com/webhooks.md) for the full delivery contract.

---

## TikTok

### Profile scraping

`scrape_tiktok_profile` runs a [background job](#background-jobs) and returns every matching video, all pages merged:

```python
result = client.scrape_tiktok_profile(
    profile_url="https://www.tiktok.com/@tiktok",
    max_posts=100,
    after_datetime="2024-01-01",
)
task_id = result.data.task_id

for video in result.data.videos or []:
    print(video.title, video.published_at, video.likes, video.url)
```

| Parameter                            | Type                        | Description                                                                          |
| ------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------ |
| `profile_url`                        | `str`                       | Public TikTok profile URL                                                            |
| `max_posts`                          | `int`                       | Stop once this many matching videos are collected                                    |
| `after_datetime` / `before_datetime` | `str` / `date` / `datetime` | Only include videos published in this window                                         |
| `min_likes` / `max_likes`            | `int`                       | Like-count filters                                                                   |
| `webhook_url`                        | `str`                       | Optional; see [Webhooks](#webhooks)                                                  |
| `limit`                              | `int`                       | Optional: return only the first page of this size (up to 500) instead of every video |
| `include_usage`, `timeout`           |                             | As for other [job methods](#background-jobs)                                         |

`video.published_at` is a Python `datetime`, and `views`, `likes`, `reposts` and `comments` are integers. To start the scrape without waiting, use `client.tiktok_profile.submit(...)`, then `job.result()`.

**Read the remaining pages** (only when you passed `limit`):

```python
pagination = result.data.pagination

while pagination and pagination.has_next:
    page = client.get_tiktok_profile_scrape(task_id, cursor=pagination.next_cursor, limit=50)
    for video in page.data.videos or []:
        print(video.title, video.url)
    pagination = page.data.pagination
```

**Or download the full result** from the short-lived (about 1 hour) `download_url`. Calling `get_tiktok_profile_scrape` again mints a fresh link.

```python
import json
from urllib.request import urlopen

if result.data.download_url:
    with urlopen(result.data.download_url) as response:
        full_profile = json.load(response)

    for video in full_profile.get("videos", []):
        print(video.get("title"), video.get("url"))  # plain dicts, not typed models
```

### Keyword search

`search_tiktok` (or `client.tiktok_search(...)`) works the same way and returns every result:

```python
result = client.search_tiktok(
    query="ai tools",
    max_results=100,
    sort_by="most_liked",
    published_within="this_month",
    min_views=1000,
)

for item in result.data.results or []:
    print(item.description, item.published_at, item.stats.views if item.stats else None, item.url)

print(result.data.stats.sort_by, result.data.stats.published_within)  # what the search actually ran with
```

| Parameter                                             | Type                        | Description                                                                                              |
| ----------------------------------------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------- |
| `query`                                               | `str`                       | Keyword phrase (at least 2 characters)                                                                   |
| `max_results`                                         | `int`                       | Cap on merged results. `0` or omitted means no cap                                                       |
| `parallel_search_slices`                              | `int`                       | `1`-`4` concurrent search chains. More slices return more unique videos but bill up to N times the pages |
| `sort_by`                                             | `str`                       | `"relevance"`, `"most_liked"` or `"newest"`                                                              |
| `published_within`                                    | `str`                       | `"all"`, `"past_24_hours"`, `"this_week"`, `"this_month"`, `"last_3_months"` or `"last_6_months"`        |
| `after_datetime` / `before_datetime`                  | `str` / `date` / `datetime` | Exact publish-date bounds                                                                                |
| `min_likes` / `max_likes` / `min_views` / `max_views` | `int`                       | Engagement filters                                                                                       |
| `country`                                             | `str`                       | Two-letter code whose results you get. Default `"gb"`; `"us"` is refused                                 |
| `webhook_url`                                         | `str`                       | Optional; see [Webhooks](#webhooks)                                                                      |
| `limit`                                               | `int`                       | Optional: return only the first page of this size (up to 500)                                            |

With `limit`, read further pages with `get_tiktok_search(task_id, cursor=...)`, exactly as for profiles. See the [Searching TikTok guide](https://docs.vidnavigator.com/guides/tiktok-search.md).

Pass `country="fr"` (or `"de"`, `"jp"`, ...) to get another country's results; the default is `"gb"`, and `"us"` is refused because TikTok asks US visitors to log in. Billing: 1 `residential_request` per 30 results returned (`result.data.stats.results_count`), minimum 1 per search and 1 per 5 pages read.

### LIVE search

> [!NOTE]
>
> New in **2.2.0**.

`search_tiktok_live` finds TikTok LIVE rooms broadcasting right now for a keyword, with their stream URLs, and returns every room:

```python
result = client.tiktok_live_search(query="gaming", country="us")

for room in result.data.results or []:
    print(room.title, room.author.unique_id, room.stats.viewers, room.category, room.hashtags)
    if room.stream_urls:
        quality = room.stream_urls.default_quality
        print("  FLV:", room.stream_urls.flv.get(quality))
        print("  HLS:", room.stream_urls.hls.get(quality))  # not every LIVE offers HLS
        print("  audio only:", room.stream_urls.audio_only)
```

| Parameter             | Type   | Description                                                           |
| --------------------- | ------ | --------------------------------------------------------------------- |
| `query`               | `str`  | Keyword phrase (at least 2 characters)                                |
| `max_results`         | `int`  | Cap on rooms. `0` or omitted means as many as TikTok serves, about 50 |
| `country`             | `str`  | Two-letter code whose LIVE rooms you get. Default `"us"`              |
| `include_stream_urls` | `bool` | Stream URLs are returned by default; `False` leaves them out          |
| `webhook_url`         | `str`  | Optional; see [Webhooks](#webhooks)                                   |
| `limit`               | `int`  | Optional: return only the first page of this size                     |

Each room (`TikTokLiveRoom`) has `id`, `url`, `author` and `stats` like a keyword result, plus `started_at` (a `datetime`), `stats.viewers` / `stats.total_viewers`, `hashtags` (the title's `#tags`), `category` (e.g. `"Gaming"`), `game_tags`, and `stream_urls`: `flv` and `hls` URLs keyed by quality (`origin`, `uhd`, `hd`, `sd`, `ld`), `default_quality`, `audio_only` and `expires_at`. The URLs play while the LIVE is on. Billing: 1 `residential_request` per 30 rooms returned (`result.data.stats.results_count`), minimum 1. Use `client.tiktok_live_search.submit(...)` (or `submit_tiktok_live_search(...)`) for a handle. See [TikTok LIVE Search](https://docs.vidnavigator.com/api-reference/endpoint/tiktok-live-search.md).

### LIVE room

> [!NOTE]
>
> New in **2.3.0**.

`get_tiktok_live_room` returns one LIVE room right away, no job: by `room_id`, `username` or `url` (exactly one):

```python
resp = client.get_tiktok_live_room(username="creator", include_comments=True)
room = resp.data.room

print(room.status, room.title, room.stats.viewers, room.stats.new_followers)
if room.is_live:
    for comment in resp.data.comments:
        print(comment.created_at, comment.author.unique_id, comment.text)
else:
    print("ended at", room.ended_at)
```

| Parameter             | Type   | Description                                                                                    |
| --------------------- | ------ | ---------------------------------------------------------------------------------------------- |
| `room_id`             | `str`  | A LIVE room id, e.g. the `id` of a LIVE search room                                            |
| `username`            | `str`  | The streamer, with or without `@`: their current LIVE, or their last one when they are offline |
| `url`                 | `str`  | `https://www.tiktok.com/@username/live`, the profile URL, or a room's `share_url`              |
| `include_comments`    | `bool` | Also return the latest comments, pinned comment, intro and top viewers. Default `False`        |
| `comments_limit`      | `int`  | At most this many comments, 1-50 (default 50)                                                  |
| `include_stream_urls` | `bool` | Stream URLs are returned by default; `False` leaves them out                                   |
| `include_usage`       | `bool` | Add the `usage` block                                                                          |

The room (`TikTokLiveRoomDetail`) has the LIVE search room fields plus `status` (`"live"` / `"ended"`, also `room.is_live`), `ended_at`, `stats.new_followers`, `author.bio`, `author.following`, `share_url`, `chat_enabled`, `subscribers_only`, `age_restricted` and `products`. It has no likes, comment count or share count: LIVE search returns those. With `include_comments=True`, `resp.data` also has `comments` (newest first; TikTok keeps only about the last 50), `pinned_comment`, `intro` and `top_viewers`. Also on `AsyncVidNavigatorClient`. A room or account that does not exist raises `NotFoundError` (`error_code == "live_not_found"`). The call may wait up to two minutes, whatever the client's `timeout`. Billing: 1 `residential_request`, 2 with `include_comments` (1 when the room has ended); not billed when the room is not found. See [TikTok LIVE Room](https://docs.vidnavigator.com/api-reference/endpoint/tiktok-live-room.md).

---

## Search

### Search YouTube

Runs a YouTube search, then ranks the results with AI analysis of their transcripts:

```python
results = client.search_youtube(
    query="how to train a neural network from scratch",
    start_year=2023,
    max_results=5,
)

print(f"Found {results.data.total_found} results")
print(results.data.explanation)

for r in results.data.results:
    print(f"{r.title} (score: {r.relevance_score})")
    print(f"  {r.transcript_summary}")
```

| Parameter                 | Type   | Description                                                                                                                                                                          |
| ------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `query`                   | `str`  | Natural-language search query                                                                                                                                                        |
| `use_enhanced_search`     | `bool` | AI-enhanced query (default: `True`)                                                                                                                                                  |
| `start_year` / `end_year` | `int`  | Only videos published in or after `start_year`, and in or before `end_year`                                                                                                          |
| `focus`                   | `str`  | What comes first among the matching videos: `"relevance"` (default, the best matches), `"recency"` (the most recent), `"popularity"` (the most viewed) or `"brevity"` (the shortest) |
| `duration`                | `int`  | Maximum duration in seconds: longer videos are left out                                                                                                                              |
| `max_results`             | `int`  | Max candidate videos to analyze; each one is billed, so this caps cost                                                                                                               |
| `include_usage`           | `bool` | Attach a per-call `usage` block                                                                                                                                                      |

> [!NOTE]
>
> `search_videos` still works as a deprecated alias for `search_youtube`.

### Search your uploaded files

```python
results = client.search_files(
    query="customer feedback about pricing",
    namespace_ids=["ns_client_calls"],  # optional: scope to specific namespaces
)

for r in results.data.results:
    print(f"{r.name} (score: {r.relevance_score})")
    print(f"  Timestamps: {r.timestamps}")
    print(f"  {r.relevant_text}")
```

---

## Files

Supported formats: mp4, webm, mov, avi, wmv, flv, mkv, m4a, mp3, mpeg, mpga, wav.

### Upload and process

```python
result = client.upload_file("./meeting.mp4", wait_for_completion=True)
file_id = result["file_id"]
print(result["file_status"])  # "completed"
```

With `wait_for_completion=False` (the default), the upload returns immediately and processing continues in the background. Check `get_file(file_id).data.file_info.status` until it is `"completed"`.

### Retrieve a file and its transcript

```python
resp = client.get_file(file_id)  # pass transcript_text=True for a single string
info = resp.data.file_info

print(f"{info.name} ({info.duration}s, {info.status})")
print(f"Namespaces: {[ns.name for ns in info.namespaces or []]}")

for segment in resp.data.transcript or []:
    print(f"[{segment.start:.1f}s] {segment.text}")
```

### List and filter files

```python
resp = client.get_files(limit=20, status="completed")
for f in resp.data.files:
    print(f"{f.name} -- {f.status}")

resp = client.get_files(namespace_id="ns_client_calls")  # filter by namespace
resp = client.get_files(limit=20, offset=20)             # paginate
print(resp.data.has_more)
```

### Manage files

```python
client.get_file_url(file_id)            # signed URL to view or download the file
client.retry_file_processing(file_id)   # retry after a failure
client.cancel_file_upload(file_id)      # cancel in-progress processing
client.delete_file(file_id)             # permanently delete
```

### Namespaces

Group uploaded files by project, client or topic, then scope listings and searches to them.

```python
ns = client.create_namespace(name="Client Calls")
print(ns.data.id)  # "ns_abc123"

for ns in client.get_namespaces().data:
    print(f"{ns.id}: {ns.name}")

client.update_namespace("ns_abc123", name="Sales Calls")

# Upload a file straight into a namespace
client.upload_file("./call.mp3", namespace_ids=["ns_abc123"])

# Reassign a file's namespaces
resp = client.update_file_namespaces(file_id, namespace_ids=["ns_abc123", "ns_def456"])
print(resp.data.namespaces)

# Delete (files are unlinked, not deleted)
client.delete_namespace("ns_abc123")
```

---

## Usage and billing

### Per-call usage

Pass `include_usage=True` to see which meters a call charged, how many credits were deducted, and how many LLM tokens were used. It is supported by `get_transcript`, `transcribe_video`, `watch_video`, `analyze_video`, `analyze_file`, `extract_video_data`, `extract_file_data`, `search_youtube`, `search_files`, `get_tweet_statement`, the TikTok methods, and `job.result(include_usage=True)`.

```python
resp = client.search_youtube(query="react best practices", include_usage=True)

usage = resp.usage
if usage:
    print(f"Credits this call: {usage.total_credits}")
    for charge in usage.charges or []:
        print(f"  {charge.service_type}: {charge.quantity} unit(s), {charge.credits} credits")

    tokens = usage.analysis_tokens  # analyze / extract / YouTube search / tweet analysis
    if tokens:
        print(f"  LLM tokens: {tokens.total_tokens}")
```

| Field                      | Description                                                                                                                        |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `charges`                  | One `UsageCharge` per meter: `service_type`, `quantity`, `credits`, `waived`, `credits_saved`, and (analysis only) nested `tokens` |
| `total_credits`            | Net credits deducted by the call                                                                                                   |
| `waived`                   | Present when a cache hit waived charges (`waived.credits_saved`)                                                                   |
| `analysis_tokens`          | LLM token counts (`prompt_tokens`, `completion_tokens`, `total_tokens`)                                                            |
| `charge_for(service_type)` | The charge for one meter, e.g. `usage.charge_for("transcription_hour")`                                                            |

Meters: `standard_request`, `residential_request`, `transcription_hour`, `frame_analysis`, `analysis_request`, `search_request` and `scene_analysis_hour`. See [Usage & Costs](https://docs.vidnavigator.com/api-reference/usage-costs.md).

### Account usage

```python
usage = client.get_usage().data

print(f"Credits: {usage.credits.monthly_remaining} / {usage.credits.monthly_total}")
print(f"Storage: {usage.storage.used_formatted} / {usage.storage.limit_formatted}")

if usage.usage:
    print(f"Standard requests: {usage.usage.standard_request.used}")
    print(f"Transcription hours: {usage.usage.transcription_hour.used}")
```

`client.health_check()` returns the API status and needs no authentication.

---

## Error handling

Every API error maps to a specific exception, all inheriting from `VidNavigatorError`:

```python
from vidnavigator import BadRequestError, NotFoundError, RateLimitExceeded, VidNavigatorError

try:
    client.get_file("nonexistent-id")
except NotFoundError:
    print("File not found")
except RateLimitExceeded:
    print("Rate limit hit -- slow down")
except VidNavigatorError as exc:
    print("Something else went wrong:", exc)
```

API exceptions carry the details of the error response:

```python
try:
    client.extract_video_data(video_url=url, schema={"x": {"type": "Nope", "description": "?"}})
except BadRequestError as exc:
    print(exc.status_code)  # 400
    print(exc.error_code)   # "invalid_schema" -- machine-readable, safe to branch on
    print(exc.docs_url)     # link to the relevant docs, when provided
    print(exc.payload)      # the full JSON error body
```

| Exception                   | Status | When                                                                                                         |
| --------------------------- | ------ | ------------------------------------------------------------------------------------------------------------ |
| `BadRequestError`           | 400    | Invalid parameters or schema                                                                                 |
| `AuthenticationError`       | 401    | Missing or invalid API key                                                                                   |
| `PaymentRequiredError`      | 402    | Not enough credits                                                                                           |
| `AccessDeniedError`         | 403    | Insufficient permissions, or content that requires login or age verification                                 |
| `NotFoundError`             | 404    | Resource not found, including an unknown or expired job `task_id`                                            |
| `StorageQuotaExceededError` | 413    | Storage quota exceeded                                                                                       |
| `RateLimitExceeded`         | 429    | Too many requests                                                                                            |
| `TooManyActiveJobsError`    | 429    | Too many background jobs already running (subclass of `RateLimitExceeded`)                                   |
| `GeoRestrictedError`        | 451    | Content unavailable in your region                                                                           |
| `SystemOverloadError`       | 503    | Temporary overload (check `.retry_after_seconds`)                                                            |
| `ServerError`               | 5xx    | Unexpected server error                                                                                      |
| `JobTimeoutError`           | --     | A blocking call or `job.result()` hit its `timeout`. The job keeps running; resume with `.job` or `.task_id` |
| `WebhookSignatureError`     | --     | A webhook delivery failed signature or timestamp verification                                                |
| `VidNavigatorError`         | --     | Base class for all errors, also raised for network failures                                                  |

See [Errors](https://docs.vidnavigator.com/api-reference/errors.md) for every API error code.

---

## What's new in 2.4.0

- **[Watch](#watch):** `watch_video` / `client.watch` reads what a video shows, next to what it says: a list of scenes (`start`, `end`, `description`, `on_screen_text`) and the transcript, in one result. `detail` sets how closely the picture is followed, `include_transcript=False` returns the scenes only. Runs as a background job like `transcribe_video`, with `submit_watch_video`, `resume_job("watch", task_id)` and the `watch.completed` / `watch.failed` webhook events. Also on `AsyncVidNavigatorClient`.

No other changes are needed to upgrade from 2.3.1.

---

## What's new in 2.3.1

- **[YouTube search](#search-youtube):** `focus="recency"` puts the most recent videos first, next to `"relevance"`, `"popularity"` and `"brevity"`. `start_year` and `end_year` bound the publication year, and `duration` is a maximum length in seconds.

No other changes are needed to upgrade from 2.3.0.

---

## What's new in 2.3.0

- **[TikTok LIVE room](#live-room):** `get_tiktok_live_room` (sync and async clients) returns one room right away, by room id, streamer or LIVE URL: live or ended, viewers, new followers, the streamer's bio, and with `include_comments=True` its latest comments, pinned comment, intro and top viewers. Typed as `TikTokLiveRoomResponse`.

No other changes are needed to upgrade from 2.2.0.

## What's new in 2.2.0

- **[TikTok LIVE search](#live-search):** `search_tiktok_live`, `submit_tiktok_live_search` and `get_tiktok_live_search` (sync and async clients), with typed rooms and their FLV / HLS / audio-only stream URLs. Job type `"tiktok_live_search"`.
- **`country` on TikTok keyword search**, echoed on the task and its `stats`, with `stats.videos_fetched` (the billed count) and the `items_*` filter counters.
- **[Operation objects](#operation-objects)**, as in the JavaScript SDK: `client.tiktok_search(...)`, `.submit(...)` and `.resume(task_id)`, for every background job.
- **TikTok results come whole:** `scrape_tiktok_profile`, `search_tiktok`, `search_tiktok_live` and `job.result()` on TikTok jobs return every item, all pages merged, like the JavaScript SDK. In 2.1.0 they returned the first 50.

To upgrade from 2.1.0: if you relied on getting only the first page of TikTok results, pass `limit=50`.

## What's new in 2.1.0

- **[Async client](#async-client):** `AsyncVidNavigatorClient` and `AsyncJob`, with the same methods as the sync client, as coroutines. Install with `pip install "vidnavigator[async]"`.
- **`video_info` on extraction:** `extract_video_data(...)` and `submit_extract_video_data(...).result()` now return the video's metadata in `resp.video_info`, and `extract_video.completed` webhook events carry it in `event.data.video_info`.
- **Python 3.8+:** support for Python 3.7 was dropped.

No other changes are needed to upgrade from 2.0.0.

## Upgrading from 1.x

Version 2.0 runs speech-to-text, extraction, tweet analysis and TikTok operations as background jobs. Most code keeps working unchanged. Check these points:

| In 1.x                                                                                        | In 2.0                                                                                                                                             |
| --------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `transcribe_video`, `extract_video_data` and `get_tweet_statement` made one long HTTP request | They submit a job and poll it. Same arguments and return types, no media duration limit. They can raise `JobTimeoutError` (default wait: one hour) |
| `extract_video_data(..., include_usage=True).usage.total_tokens`                              | Use `usage.analysis_tokens.total_tokens`                                                                                                           |
| `submit_tiktok_profile_scrape` / `submit_tiktok_search` returned the submit response          | They return a `Job`. `job.data.task_id` still works; **`job.status` is now a method**                                                              |
| Manual polling loops on `get_tiktok_profile_scrape`                                           | `scrape_tiktok_profile(...)`, or `job.result()` on a submitted job                                                                                 |
| `task.data.error_message` on failed TikTok tasks                                              | Deprecated; read `task.data.error` (`error`, `message`, `http_status`), or let `job.result()` raise                                                |
| `search_videos(...)`                                                                          | `search_youtube(...)` (the old name is a deprecated alias)                                                                                         |
| A 401 raised the generic `VidNavigatorError`                                                  | It raises `AuthenticationError`                                                                                                                    |

**New in 2.0:** `submit_transcribe_video`, `submit_extract_video_data`, `submit_tweet_statement`, `scrape_tiktok_profile`, `search_tiktok`, `resume_job`, `webhook_url` on every job method, `sort_by` and `published_within` for TikTok search, the webhook helpers, and `status_code` / `error_code` / `docs_url` / `payload` on every API exception.

---

## Resources

> [card] [PyPI](https://pypi.org/project/vidnavigator/)
>
> Package page and release history.

> [card] [GitHub](https://github.com/vidnavigator/vidnavigator-python)
>
> Source code and issue tracker.

> [card] [JavaScript SDK](https://docs.vidnavigator.com/sdks/javascript.md)
>
> The same API for Node.js and TypeScript.

> [card] [API Reference](https://docs.vidnavigator.com/api-reference/introduction.md)
>
> Every endpoint, parameter and response field.
