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

# Cut clips from a video link by what's said, in Python

> A Python script for clipping tools: one Importly job returns the video file and a timestamped transcript, then your app finds every sentence with a phrase and cuts each one into its own MP4 with ffmpeg.

A clipping tool, highlight reel or repurposing app needs two things from a link: the full video file and a transcript with timestamps, so it can find the moment and cut it. Getting the file yourself means a download tool that gets blocked on servers, and getting the timestamps means a separate speech-to-text step. One Importly import returns both. This script takes a link and a phrase, finds every sentence where it's said, and cuts each one into its own MP4 with ffmpeg on your machine or server. Importly delivers the file and the transcript; your app does the cutting, so you control the edit.

## The code

```python cut_clips.py theme={null}
import os
import re
import subprocess
import sys
import time

import httpx

URL, PHRASE = sys.argv[1], sys.argv[2]
PAD = 0.5  # seconds of context before and after each sentence

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

def import_with_transcript(url: str) -> dict:
    res = api.post("/import", json={
        "url": url,
        "videoQuality": "720p",
        "compatibleCodecs": True,          # H.264 + AAC: plays and edits everywhere
        "includeTranscript": True,
        "transcriptMode": "ai",            # speech-to-text: sentence-level timestamps
        "maxCostDollars": 1.00,
    })
    body = res.json()
    if not res.is_success or not body.get("success"):
        sys.exit(f"Import not started: {body.get('code')} {body.get('error')}")

    job_id = body["data"]["jobId"]
    while True:
        data = api.get("/import/status", params={"id": job_id}).json()["data"]
        if data["status"] == "completed":
            return data["result"]
        if data["status"] == "failed":
            sys.exit(f"Import failed: {data.get('code')} {data.get('message')}")
        time.sleep(5)

def matching_segments(transcript: dict, phrase: str) -> list[dict]:
    needle = phrase.lower()
    return [s for s in transcript["data"]["segments"] if needle in s["text"].lower()]

def download(media_url: str, path: str) -> None:
    with httpx.stream("GET", media_url, timeout=None, follow_redirects=True) as r:
        r.raise_for_status()
        with open(path, "wb") as f:
            for chunk in r.iter_bytes():
                f.write(chunk)

def cut(source: str, start: float, end: float, out: str) -> None:
    # Re-encode so the clip starts exactly on the sentence, not on the nearest keyframe
    subprocess.run([
        "ffmpeg", "-y", "-loglevel", "error",
        "-ss", f"{max(start - PAD, 0):.2f}", "-to", f"{end + PAD:.2f}",
        "-i", source,
        "-c:v", "libx264", "-preset", "veryfast", "-c:a", "aac",
        out,
    ], check=True)

result = import_with_transcript(URL)
transcript = result.get("transcript") or {}
if transcript.get("status") == "skipped":
    sys.exit(f"No transcript: {transcript.get('reason')}")

matches = matching_segments(transcript, PHRASE)
if not matches:
    sys.exit(f'"{PHRASE}" isn\'t said in "{result["title"]}"')

os.makedirs("clips", exist_ok=True)
download(result["mediaUrl"], "clips/source.mp4")
for i, seg in enumerate(matches, start=1):
    slug = re.sub(r"[^a-z0-9]+", "-", PHRASE.lower()).strip("-")
    out = f"clips/{slug}-{i}.mp4"
    cut("clips/source.mp4", seg["start"], seg["end"], out)
    print(f'{out}  {seg["start"]:.1f}-{seg["end"]:.1f}s  "{seg["text"]}"')

print(f"Cost: ${result['totalCostInDollars']}")
```

```bash theme={null}
pip install httpx   # and ffmpeg: apt install ffmpeg, or brew install ffmpeg
export IMPORTLY_API_KEY=your_api_key

python cut_clips.py "https://www.youtube.com/watch?v=jNQXAC9IVRw" "elephants"
```

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.

Output for that link:

```text theme={null}
clips/elephants-1.mp4  1.5-3.5s  "So here we are, one of the, elephants."
Cost: $0.02
```

## How it works

One job, file and transcript. `includeTranscript: true` with `transcriptMode: "ai"` runs speech-to-text on the same import, so the result has `mediaUrl` (the video) and `transcript.data.segments`, one segment per sentence with `start` and `end` in seconds. The download and the transcript are billed together; `totalCostInDollars` is what the job cost.

`compatibleCodecs: true` asks for H.264 video and AAC audio, which every editor, browser and phone plays. Without it you may get a smaller AV1 or VP9 file at the same resolution.

`maxCostDollars` caps the job. A long video at 720p plus speech-to-text costs more than a short clip, and a job that would go over fails with `MAX_COST_EXCEEDED` before anything is charged.

The cut re-encodes. Copying the stream (`-c copy`) is faster but starts on the nearest keyframe, which can be seconds before the sentence. Re-encoding a short clip takes a moment and starts where the sentence does. `PAD` adds half a second either side so words aren't clipped.

The match is a plain substring search over each sentence. Swap `matching_segments` for whatever your app does: a list of keywords, a search index over segments, or an LLM that picks the best moments from the transcript text and returns their timestamps.

## Errors to handle

| Where | What you see | What to do |
| - | - | - |
| Start request | HTTP `402` `INSUFFICIENT_BALANCE` | Add credits; nothing was charged. Or set `fitQualityToBalance: true` to fall back to a lower quality |
| Start request | HTTP `429` `RATE_LIMITED` | Wait `retryAfter` seconds. See [Rate limits](/docs/error-handling.md#rate-limits) |
| Status | `status: "failed"`, `code: "VIDEO_UNAVAILABLE"` | The video is gone, private or region-locked. Show the user the message |
| Status | `status: "failed"`, `code: "MAX_COST_EXCEEDED"` | The video is longer than your cap allows. Raise `maxCostDollars` or lower `videoQuality` |
| Result | `transcript.status: "skipped"` | The file arrived but there's no transcript; `transcript.reason` says why |
| Download | An error on `mediaUrl` after a week | The link expires after 7 days. Store the file in your own bucket if you need it longer |

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

## In production

Don't poll in a web request. Start the import from your API route, pass a `webhookUrl`, and cut the clips in a background worker when Importly calls back. See [Webhooks](/docs/webhooks.md).

Keep the source video. Add `store: true` and a `storagePath` so the file also lands in your own bucket, and cut from there whenever a user asks for a new clip, without importing again. See [Save to your bucket](/docs/integrations/save-to-bucket.md).

Captions are cheaper when the video has them. Send `transcriptMode: "captions"` (or `"auto"`, the default, for captions with speech-to-text when there are none) and `transcriptLanguage` to use the platform's captions (line-by-line timing, sometimes auto-generated). See [Transcripts](/docs/features/transcripts.md).

> [!NOTE]
>
> A 10-minute 720p video (about 77 MB) costs about $0.15 to import, and $0.10 more for the speech-to-text transcript. 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.