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

# Build a speech dataset from a list of links in Python

> A Python script that turns a file of video and audio links into a training set: the audio lands in your own bucket, and a JSONL manifest holds each clip's key, transcript and timestamped segments.

A speech or audio model needs two things per example: the audio file and the text that goes with it. When the sources are links (talks, interviews, podcasts, lectures), collecting them yourself means a download tool that breaks on servers, an audio converter, a speech-to-text account, and a bucket upload step. This script reads a file of links, imports each one as audio with a transcript, has Importly copy the audio straight into your bucket, and writes a manifest you can load with any training stack. Run it again after adding links: finished clips are skipped, and jobs still running are collected.

Use media you have the right to use for training, such as your own content, licensed content, or sources whose terms allow it.

## Before you start

Connect your bucket once: Amazon S3, Cloudflare R2, Backblaze B2, DigitalOcean Spaces or Supabase Storage. Save it on the dashboard's [S3 Storage](https://www.importly.io/dashboard/s3-storage) page or with one API call (see [Deliver to your bucket](/docs/s3-storage.md)). Every import with `store: true` then lands there.

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it's shown once) and keep it on the machine that runs the script.

## The code

```python build_dataset.py theme={null}
import hashlib
import json
import os
import sqlite3
import sys

import httpx

LINKS_FILE = sys.argv[1]  # one media link per line
DATASET = os.environ.get("DATASET", "speech-v1")
MAX_COST = float(os.environ.get("MAX_COST_PER_LINK", "0.50"))  # about 45 minutes of audio
LANGUAGE = os.environ.get("LANGUAGE", "en")
MAX_NEW_PER_RUN = 50
MIN_WORDS_PER_MINUTE = 40  # speech runs about 120-160

api = httpx.Client(
    base_url="https://api.importly.io",
    headers={"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"},
    timeout=30,
)

db = sqlite3.connect(f"{DATASET}.db")
db.execute("""
    create table if not exists clips (
        url text primary key,
        job_id text,
        status text,
        result text,
        error text
    )
""")

def clip_id(url: str) -> str:
    """A stable file name per link. Titles repeat, so don't name files by title."""
    return hashlib.sha256(url.encode()).hexdigest()[:16]

def start_new_links() -> None:
    with open(LINKS_FILE) as f:
        links = [line.strip() for line in f if line.strip() and not line.startswith("#")]
    started = 0
    for url in links:
        if db.execute("select 1 from clips where url = ?", (url,)).fetchone():
            continue  # already started, done or failed
        if started >= MAX_NEW_PER_RUN:
            break

        res = api.post("/import", json={
            "url": url,
            "includeVideo": False,             # audio only
            "audioQuality": "medium",          # up to 128 kbps
            "includeTranscript": True,
            "transcriptMode": "ai",            # speech-to-text, one segment per sentence
            "transcriptLanguage": LANGUAGE,
            "maxCostDollars": MAX_COST,        # download plus transcript, per link
            "store": True,                     # copy the audio into your bucket
            "storagePath": f"datasets/{DATASET}/audio",
            "storageFilename": clip_id(url),
        })
        body = res.json()
        if res.status_code in (402, 429):
            # Out of credits, or the hourly or in-progress limit: the rest wait for the next run
            print(f"Stopping for this run: {body.get('code')} {body.get('error')}")
            return
        if not res.is_success or not body.get("success"):
            # A link Importly can't take. Record it so it isn't sent again.
            db.execute(
                "insert into clips (url, status, error) values (?, 'failed', ?)",
                (url, f"{body.get('code')}: {body.get('error')}"),
            )
            db.commit()
            continue

        db.execute(
            "insert into clips (url, job_id, status) values (?, ?, ?)",
            (url, body["data"]["jobId"], body["data"]["status"]),
        )
        db.commit()
        started += 1
        print(f"Started: {url}")

def collect_finished() -> None:
    pending = db.execute(
        "select url, job_id from clips where status in ('queued', 'running')"
    ).fetchall()
    for url, job_id in pending:
        data = api.get("/import/status", params={"id": job_id}).json()["data"]
        if data["status"] == "completed":
            db.execute(
                "update clips set status = 'completed', result = ? where url = ?",
                (json.dumps(data["result"]), url),
            )
        elif data["status"] == "failed":
            # e.g. VIDEO_UNAVAILABLE or MAX_COST_EXCEEDED. Failed imports aren't charged.
            db.execute(
                "update clips set status = 'failed', error = ? where url = ?",
                (f"{data.get('code')}: {data.get('message')}", url),
            )
        db.commit()

def write_manifest() -> None:
    """One JSON line per clip that has its audio in your bucket and a transcript."""
    rows = db.execute("select url, result from clips where status = 'completed'").fetchall()
    kept = 0
    with open(f"{DATASET}.jsonl", "w") as out:
        for url, result_json in rows:
            result = json.loads(result_json)
            transcript = result.get("transcript") or {}
            stored = result.get("s3Storage")
            if not stored or transcript.get("status") == "skipped":
                continue  # the stored result has s3StorageError or transcript.reason
            minutes = (result.get("duration") or 0) / 60
            if minutes and len(transcript["text"].split()) / minutes < MIN_WORDS_PER_MINUTE:
                continue  # mostly music or silence: a few stray words, not speech
            out.write(json.dumps({
                "audio": stored["key"],
                "source_url": url,
                "title": result.get("title"),
                "duration": result.get("duration"),
                "language": transcript.get("language"),
                "text": transcript["text"],
                "segments": transcript["data"]["segments"],
                "cost": result.get("totalCostInDollars"),
            }) + "\n")
            kept += 1
    print(f"{DATASET}.jsonl: {kept} clips")

collect_finished()
start_new_links()
write_manifest()
```

```bash theme={null}
pip install httpx
export IMPORTLY_API_KEY=your_api_key

# links.txt: one link per line (YouTube, Vimeo, SoundCloud, podcast episodes, direct audio files...)
DATASET=interviews-v1 python build_dataset.py links.txt
```

Run it every few minutes (cron, a scheduled worker, or by hand) until every link is done. Each run collects finished jobs, starts up to 50 new links, and rewrites the manifest.

## What you get

The audio is in your bucket under `datasets/<DATASET>/audio/<clip id>.mp3`, and `<DATASET>.jsonl` has one line per clip:

```json theme={null}
{
  "audio": "datasets/interviews-v1/audio/4b0f48e4f4ae6e02.mp3",
  "source_url": "https://www.youtube.com/watch?v=jNQXAC9IVRw",
  "title": "Me at the zoo",
  "duration": 19,
  "language": "en",
  "text": "Alright. So here we are, one of the, elephants. Cool thing about these guys is that ...",
  "segments": [
    { "start": 1.2, "end": 1.52, "text": "Alright." },
    { "start": 1.52, "end": 3.54, "text": "So here we are, one of the, elephants." },
    { "start": 5.2, "end": 14.129, "text": "Cool thing about these guys is that ..." }
  ],
  "cost": 0.02
}
```

Segment times are in seconds, one segment per sentence, so you can cut the audio into sentence-level examples with any audio library, or keep whole clips with their full text. Keep the manifest, not Importly's `mediaUrl`: that link expires after 7 days, and the copy in your bucket is yours.

## How it works

`includeVideo: false` downloads only the audio, so you pay for the audio stream, not the video. The file arrives as MP3.

`transcriptMode: "ai"` runs speech-to-text on every clip, so every example gets the same kind of sentence-level segments. If you'd rather use the platform's captions where they exist (cheaper, but line-by-line timing and sometimes auto-generated), send `transcriptMode: "auto"` (the default) instead: captions when the clip has them, speech-to-text when it doesn't. See [Transcripts](/docs/features/transcripts.md).

`maxCostDollars` caps each link, the download and the transcript together. A link that would go over fails with `MAX_COST_EXCEEDED` and isn't charged.

`storageFilename` names the file after a hash of the link. Without it the file is named after the media title, and two clips with the same title would land on the same key.

Each link is sent once. The link is the key in SQLite, so re-running the script never imports a clip twice, and failed links stay recorded with their error code.

## Errors to handle

| Where | What you see | What the script does |
| - | - | - |
| Start request | HTTP `402` `INSUFFICIENT_BALANCE` | Stops starting links until the next run. Add credits; nothing was charged |
| Start request | HTTP `429` `RATE_LIMITED` | Stops until the next run. You hit the hourly limit or the in-progress limit. See [Rate limits](/docs/error-handling.md#rate-limits) |
| Start request | HTTP `400` | Records the link as failed so it isn't sent again |
| Status | `status: "failed"`, `code: "VIDEO_UNAVAILABLE"` | Records it. The link is gone, private or a 404 |
| Status | `status: "failed"`, `code: "DRM_PROTECTED"` | Records it. The source is DRM-protected and can't be downloaded |
| Status | `status: "failed"`, `code: "MAX_COST_EXCEEDED"` | Records it. Raise `MAX_COST_PER_LINK` and delete the row to retry |
| Result | `s3StorageError` | Leaves it out of the manifest. The bucket refused the upload; check its settings with [`POST /s3-storage/test`](/docs/endpoints/test-s3-storage) |
| Result | `transcript.status: "skipped"` | Leaves it out of the manifest. `transcript.reason` says why |
| Result | A handful of words for minutes of audio | Leaves it out of the manifest (`MIN_WORDS_PER_MINUTE`). On music or silence, speech-to-text returns a few stray words, not an empty transcript |

Every error has a `documentationUrl` with the fix. See [Error handling](/docs/error-handling.md).

## In production

Thousands of links? Raise `MAX_NEW_PER_RUN` slowly: a `429` just moves the rest to the next run. Pass a `webhookUrl` with each import to save results as they finish instead of polling, and keep the status check as a fallback. See [Webhooks](/docs/webhooks.md).

Need video too, for a video model or evals? Drop `includeVideo: false` and set `videoQuality` (for example `"480p"`). See [`POST /import`](/docs/endpoints/import) for the quality options.

> [!NOTE]
>
> A 10-minute talk costs about $0.12 here: around $0.02 for the audio download and \$0.10 for speech-to-text. Status checks are free. Try it free, no card required. See [Pricing & credits](/docs/billing.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.