> ## 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 Node

> A Node.js 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. It runs on Node 18 or later with no npm dependencies. The [Python version](/docs/recipes/speech-dataset-python.md) does the same with `httpx` and SQLite.

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

```js build-dataset.mjs theme={null}
import { createHash } from 'node:crypto'
import { existsSync, readFileSync, writeFileSync } from 'node:fs'

const LINKS_FILE = process.argv[2] // one media link per line
const DATASET = process.env.DATASET ?? 'speech-v1'
const MAX_COST = Number(process.env.MAX_COST_PER_LINK ?? '0.50') // about 45 minutes of audio
const LANGUAGE = process.env.LANGUAGE ?? 'en'
const MAX_NEW_PER_RUN = 50
const MIN_WORDS_PER_MINUTE = 40 // speech runs about 120-160

const API = 'https://api.importly.io'
const headers = {
  Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
  'Content-Type': 'application/json',
}

// One entry per link: { jobId, status, result, error }. The link is the key.
const STATE_FILE = `${DATASET}.state.json`
const clips = existsSync(STATE_FILE) ? JSON.parse(readFileSync(STATE_FILE, 'utf8')) : {}
const save = () => writeFileSync(STATE_FILE, JSON.stringify(clips, null, 2))

// A stable file name per link. Titles repeat, so don't name files by title.
const clipId = (url) => createHash('sha256').update(url).digest('hex').slice(0, 16)

const startNewLinks = async () => {
  const links = readFileSync(LINKS_FILE, 'utf8')
    .split('\n')
    .map((line) => line.trim())
    .filter((line) => line && !line.startsWith('#'))
  let started = 0
  for (const url of links) {
    if (clips[url]) continue // already started, done or failed
    if (started >= MAX_NEW_PER_RUN) break

    const res = await fetch(`${API}/import`, {
      method: 'POST',
      headers,
      body: JSON.stringify({
        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: `datasets/${DATASET}/audio`,
        storageFilename: clipId(url),
      }),
    })
    const body = await res.json()
    if (res.status === 402 || res.status === 429) {
      // Out of credits, or the hourly or in-progress limit: the rest wait for the next run
      console.log(`Stopping for this run: ${body.code} ${body.error}`)
      return
    }
    if (!res.ok || !body.success) {
      // A link Importly can't take. Record it so it isn't sent again.
      clips[url] = { status: 'failed', error: `${body.code}: ${body.error}` }
      save()
      continue
    }

    clips[url] = { jobId: body.data.jobId, status: body.data.status }
    save()
    started += 1
    console.log(`Started: ${url}`)
  }
}

const collectFinished = async () => {
  for (const [url, clip] of Object.entries(clips)) {
    if (clip.status !== 'queued' && clip.status !== 'running') continue
    const res = await fetch(`${API}/import/status?id=${clip.jobId}`, { headers })
    const { data } = await res.json()
    if (data.status === 'completed') {
      clips[url] = { ...clip, status: 'completed', result: data.result }
    } else if (data.status === 'failed') {
      // e.g. VIDEO_UNAVAILABLE or MAX_COST_EXCEEDED. Failed imports aren't charged.
      clips[url] = { ...clip, status: 'failed', error: `${data.code}: ${data.message}` }
    }
    save()
  }
}

// One JSON line per clip that has its audio in your bucket and a transcript.
const writeManifest = () => {
  const lines = []
  for (const [url, clip] of Object.entries(clips)) {
    if (clip.status !== 'completed') continue
    const { result } = clip
    const transcript = result.transcript ?? {}
    const stored = result.s3Storage
    if (!stored || transcript.status === 'skipped') continue // see s3StorageError or transcript.reason
    const minutes = (result.duration ?? 0) / 60
    if (minutes && transcript.text.split(/\s+/).length / minutes < MIN_WORDS_PER_MINUTE) {
      continue // mostly music or silence: a few stray words, not speech
    }
    lines.push(JSON.stringify({
      audio: stored.key,
      source_url: url,
      title: result.title,
      duration: result.duration,
      language: transcript.language,
      text: transcript.text,
      segments: transcript.data.segments,
      cost: result.totalCostInDollars,
    }))
  }
  writeFileSync(`${DATASET}.jsonl`, lines.map((line) => line + '\n').join(''))
  console.log(`${DATASET}.jsonl: ${lines.length} clips`)
}

await collectFinished()
await startNewLinks()
writeManifest()
```

```bash theme={null}
export IMPORTLY_API_KEY=your_api_key

# links.txt: one link per line (YouTube, Vimeo, SoundCloud, podcast episodes, direct audio files...)
DATASET=interviews-v1 node build-dataset.mjs 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": "All right, so here we are, one of the elephants. Cool thing about these guys is that ...",
  "segments": [
    { "start": 1.36, "end": 3.6, "text": "All right, so here we are, one of the elephants." },
    { "start": 5.2, "end": 12.72, "text": "Cool thing about these guys is that ..." },
    { "start": 12.8, "end": 14, "text": "And that's cool." }
  ],
  "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 `<DATASET>.state.json`, so re-running the script never imports a clip twice, and failed links stay recorded with their error code. For tens of thousands of links, move that state into your database or `node:sqlite`; the logic stays the same.

## 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 link's entry in the state file 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.