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

# Transcribe new podcast episodes from an RSS feed in Python

> A Python script you run on a schedule: it reads a podcast's RSS feed, sends each new episode to speech-to-text with a cost cap, and stores the transcript and timestamps in SQLite, once per episode.

Podcast audio has no captions, so a podcast app that shows transcripts, writes show notes or searches inside episodes needs speech-to-text on every new episode. Doing that yourself means fetching each audio file, keeping a speech-to-text account, and tracking which episodes are done. This script reads the show's RSS feed, sends each new episode's audio link to Importly's [transcripts](/docs/features/transcripts.md) endpoint, and saves the text and timestamped segments in SQLite. Run it from cron or a scheduled worker: each run collects the transcripts that finished and starts the episodes that are new.

## The code

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

import feedparser
import httpx

FEED_URL = sys.argv[1]
MAX_COST = float(os.environ.get("MAX_COST_PER_EPISODE", "1.50"))  # 150 minutes at $0.01/min
MAX_NEW_PER_RUN = 10

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

db = sqlite3.connect("episodes.db")
db.execute("""
    create table if not exists episodes (
        guid text primary key,
        title text,
        audio_url text,
        job_id text,
        status text,
        transcript text,
        segments text,
        cost real,
        error text
    )
""")

def audio_url(entry) -> str | None:
    """The episode's audio file, from the RSS <enclosure>."""
    for enclosure in entry.get("enclosures", []):
        if enclosure.get("type", "").startswith("audio/"):
            return enclosure.get("href")
    return None

def start_new_episodes() -> None:
    feed = feedparser.parse(FEED_URL)
    started = 0
    for entry in feed.entries:
        guid = entry.get("id") or entry.get("link")
        url = audio_url(entry)
        if not guid or not url:
            continue
        if db.execute("select 1 from episodes where guid = ?", (guid,)).fetchone():
            continue  # already started or done
        if started >= MAX_NEW_PER_RUN:
            break

        res = api.post("/transcribe", json={
            "url": url,
            "mode": "ai",                # podcast audio has no captions
            "maxCostDollars": MAX_COST,  # the most one episode may cost
            "language": "en",
        })
        body = res.json()
        if res.status_code in (402, 429):
            # Out of credits, or the hourly or in-progress limit: try the rest 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 episodes (guid, title, audio_url, status, error) values (?, ?, ?, 'failed', ?)",
                (guid, entry.get("title"), url, body.get("error")),
            )
            db.commit()
            continue

        db.execute(
            "insert into episodes (guid, title, audio_url, job_id, status) values (?, ?, ?, ?, ?)",
            (guid, entry.get("title"), url, body["data"]["jobId"], body["data"]["status"]),
        )
        db.commit()
        started += 1
        print(f"Started: {entry.get('title')}")

def collect_finished() -> None:
    pending = db.execute(
        "select guid, job_id from episodes where status in ('queued', 'running')"
    ).fetchall()
    for guid, job_id in pending:
        data = api.get("/transcribe/status", params={"id": job_id}).json()["data"]
        if data["status"] == "completed":
            result = data["result"]
            db.execute(
                "update episodes set status = 'completed', transcript = ?, segments = ?, cost = ? where guid = ?",
                (result["text"], json.dumps(result["data"]["segments"]), result["costInDollars"], guid),
            )
        elif data["status"] == "failed":
            # e.g. MAX_COST_EXCEEDED for an episode longer than your cap. Not charged.
            db.execute(
                "update episodes set status = 'failed', error = ? where guid = ?",
                (f"{data.get('code')}: {data.get('message')}", guid),
            )
        db.commit()

collect_finished()
start_new_episodes()
```

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

# Run it every 15 minutes with the show's feed URL
python transcribe_feed.py https://example.com/your-show/feed.xml
```

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

## How it works

The audio link comes from the feed. Each RSS item has an `<enclosure>` with a link to the episode's audio file. Importly takes direct media links like these, as well as episode pages on [supported sites](/docs/features/supported-sites.md).

`"mode": "ai"` goes straight to speech-to-text. Podcast audio has no captions, so there's nothing to check first. For a feed of videos that might have captions, send `"mode": "auto"` instead: captions cost \$0.003 and speech-to-text only runs when there are none.

`maxCostDollars` caps each episode. Speech-to-text is $0.01 per minute, so the default of $1.50 covers episodes up to 150 minutes. A longer episode fails with `MAX_COST_EXCEEDED` and isn't charged. When the length isn't known up front, the cap is held while the episode is transcribed and the unused part is refunded.

Each episode is sent once. The episode's `guid` is the key in SQLite, so a re-run skips everything already started, finished or failed. Unfinished jobs are picked up by the next run, so no run sits waiting on a long episode.

Set `language` to the show's language (a two-letter code like `es`). Without it, speech-to-text transcribes as English.

## What gets stored

A finished job from `GET /transcribe/status` has the transcript under `result`. The script stores `text`, the `segments` as JSON, and `costInDollars`:

```json theme={null}
{
  "text": "Welcome back to the show...",
  "source": "importly",
  "language": "en",
  "duration": 1834,
  "data": {
    "segments": [
      { "start": 0.4, "end": 3.1, "text": "Welcome back to the show." }
    ]
  },
  "costInDollars": 0.31
}
```

Segment times are in seconds, one segment per sentence, so you can link a search hit or a quote to the moment it was said.

## Errors to handle

| Where | What you see | What the script does |
| - | - | - |
| Start request | HTTP `402` `INSUFFICIENT_BALANCE` | Stops starting episodes 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 have 50 transcriptions queued or running. See [Rate limits](/docs/error-handling.md#rate-limits) |
| Start request | HTTP `400` | Records the episode as failed so it isn't sent again. Usually a link that isn't a media file or page |
| Status | `status: "failed"`, `code: "MAX_COST_EXCEEDED"` | Records it. Raise `MAX_COST_PER_EPISODE` and delete the row to retry |
| Status | `status: "failed"` with another `code` | Records it. The audio link is gone or can't be fetched. Failed transcriptions are refunded |

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

## In production

Use a webhook instead of polling. Pass a `webhookUrl` when you start each episode and save the transcript when Importly calls you back. Keep the status check as a fallback. See [Webhooks](/docs/webhooks.md).

Many feeds? Loop over them in the same run. `MAX_NEW_PER_RUN` keeps a back catalog from starting hundreds of jobs at once, and a `429` just moves the rest to the next run.

Want the audio file too? Send the episode to [`POST /import`](/docs/endpoints/import) with `includeTranscript: true` and `transcriptProvider: "importly"` and you get the file in your bucket and the transcript from one job. See [Save to your bucket](/docs/integrations/save-to-bucket.md).

Your own speech-to-text key? Add `"provider": "deepgram"` (or `assemblyai`, `openai`) and `"apiKey"` to pay \$0.005 per minute plus your provider's fees.

> [!NOTE]
>
> A 30-minute episode costs \$0.30 with Importly speech-to-text, and 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.