DEV Community

Yusuf Yildiz
Yusuf Yildiz

Posted on Originally published at importly.io

Adding paste-a-link transcripts to a FastAPI app that keep working on a server

Plenty of Python apps end up wanting the same feature: a user sends a YouTube, TikTok or podcast link and you need the transcript, to summarize it, index it or hand it to a model. The first version usually uses a captions library and works fine on your machine.

Then you deploy it. Requests from cloud servers get blocked or asked to sign in, so code that worked locally starts failing in production. And a lot of videos have no captions, so you also need speech-to-text, which means downloading audio and wiring up a second service.

I built Importly for this, so that's what this post uses. You send it a link and get back the transcript, the file or the metadata, and it works from servers. Here's the FastAPI version. The calls are plain HTTP, so they move to Flask, Django or a worker as they are.

The key and two packages

Create a key in the dashboard, keep it in your server's environment, and install what the code uses:

export IMPORTLY_API_KEY=your_api_key
pip install fastapi httpx
Enter fullscreen mode Exit fullscreen mode

Start the transcript

mode: "auto" uses captions when the video has them and falls back to speech-to-text when it doesn't. wait holds the request until the transcript is ready, so a captioned video normally comes back in this one call. maxCostDollars stops a long uncaptioned video before it's charged.

import os

import httpx
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()
importly = httpx.AsyncClient(
    base_url="https://api.importly.io",
    headers={"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"},
    timeout=70,  # longer than the 25s wait
)


class TranscribeIn(BaseModel):
    url: str


def to_result(data: dict) -> dict:
    result = data.get("result") or {}
    return {
        "jobId": data.get("jobId"),
        "status": data.get("status"),
        "text": result.get("text"),
        "segments": (result.get("data") or {}).get("segments"),
        "code": data.get("code"),
        "message": data.get("message"),
    }


@app.post("/transcribe")
async def transcribe(payload: TranscribeIn):
    res = await importly.post(
        "/transcribe",
        json={"url": payload.url, "mode": "auto", "wait": 25, "maxCostDollars": 0.5},
    )
    body = res.json()
    if res.is_error or not body.get("success"):
        return {"status": "failed", "message": body.get("error"), "code": body.get("code")}
    return to_result(body["data"])
Enter fullscreen mode Exit fullscreen mode

A bad link, a bad key or a low balance comes back straight away with an error and a code (a wrong key gives UNAUTHORIZED). A job that fails later, say a private video, comes back with status: "failed" and a code.

Poll when it takes longer

A long video without captions can take longer than wait. Then you get status: "queued" or "running" and a jobId, and your frontend asks this endpoint every few seconds:

@app.get("/transcribe/{job_id}")
async def transcribe_status(job_id: str):
    res = await importly.get("/transcribe/status", params={"id": job_id})
    body = res.json()
    if res.is_error or not body.get("success"):
        return {"status": "failed", "message": body.get("error"), "code": body.get("code")}
    return to_result(body["data"])
Enter fullscreen mode Exit fullscreen mode

segments is the same transcript with start and end times in seconds. That's the part you want if you're chunking for a vector store or linking to timestamps.

In production, use a webhook

When the transcript belongs to a row in your database, start the job with a webhookUrl and store the jobId on the row. When the callback arrives, I only take the jobId from it and read the result from the API with my own key, so a forged request can't write into the app. Deliveries are also signed if you'd rather reject them up front.

Two things worth knowing: the webhook URL has to be public https://, so it does nothing on localhost (poll in development), and each job gets one delivery, so a small sweep for jobs pending more than a few minutes is worth having.

What it costs

A transcript from captions is $0.003. Speech-to-text for a video without captions is $0.01 a minute. It's free to try, no card required.

The full recipe, with the webhook handler and downloading the file instead of the transcript, is here: Add transcripts to a Python app.

Top comments (0)