跳转到正文
中文
获取 API 密钥
浏览文档

示例

获取带时间戳的字幕

保存已有 YouTube 字幕轨道的文本、时间和语言,为每个片段添加视频链接,供应用或智能体回答引用。

本页内容

开始前准备

需要具有 youtube_captions 权限的密钥和可用额度。选择 Python 3.10+ 与 requests,或 Bash、cURL 7.76+ 与 jq。Windows 的 Bash 版本请使用 Git Bash。

1. 选择视频和字幕轨道

创建 timestamped-captions 文件夹,将 request.json 保存到其中,并在该文件夹打开终端。将 video_id 替换为视频的 11 位 ID,不要使用完整 URL。

本例请求英文自动字幕。auto=true 时,en 先尝试 en-orig,再尝试 en。显式 -orig 代码和 auto=false 保持精确选择。API 不会在自动字幕与上传者字幕之间切换。

timestamped-captions/request.json
{
  "source": "youtube_captions",
  "video_id": "FUfGcZ092b0",
  "params": {
    "language": "en",
    "auto": true
  }
}

2. 获取并保存字幕

选择一种版本,将脚本保存到 request.json 旁。它读取 FLASHDATA_API_KEY,或通过隐藏输入提示获取密钥。智能体应从密钥存储加载该环境变量。

将 track-001 作为输出文件夹运行。新文件夹发送一次查询,并保存返回的用量。创建 captions.json 前,脚本会核对返回的视频 ID、语言、字幕来源及片段时间。

安装到 Python 环境
python -m pip install requests
timestamped-captions/captions.py
import argparse
import getpass
import json
import math
import os
import re
from datetime import datetime, timezone
from pathlib import Path

import requests

parser = argparse.ArgumentParser()
parser.add_argument("folder", help="New output folder, or an existing saved caption request")
out = Path(parser.parse_args().folder)

if not out.exists():
    body = Path("request.json").read_bytes()
    request = json.loads(body)
    if (not isinstance(request, dict) or request.get("source") != "youtube_captions"
            or not isinstance(request.get("video_id"), str)
            or not re.fullmatch(r"[A-Za-z0-9_-]{11}", request["video_id"])):
        raise SystemExit("Use youtube_captions and an 11-character video_id")
    options = request.get("params")
    if (not isinstance(options, dict) or not isinstance(options.get("language"), str)
            or not re.fullmatch(r"[A-Za-z0-9-]{1,35}", options["language"])
            or type(options.get("auto")) is not bool):
        raise SystemExit("Set one language code and auto: true or false explicitly")
    key = os.environ.get("FLASHDATA_API_KEY") or getpass.getpass("FlashData API key: ")
    if not key.strip():
        raise SystemExit("An API key is required")
    out.mkdir()
    (out / "request.json").write_bytes(body)
    (out / "requested-at.txt").write_text(
        datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), encoding="utf-8"
    )
    try:
        response = requests.post(
            "https://data.flashdata.dev/v1/queries/realtime",
            headers={"X-API-Key": key, "Content-Type": "application/json",
                     "Accept": "application/json"},
            data=body, timeout=120, allow_redirects=False,
        )
    except requests.RequestException:
        raise SystemExit(f"Request interrupted. Keep {out} and check History before retrying.")
    (out / "result.json").write_bytes(response.content)
    (out / "response-headers.txt").write_text(
        "\n".join(f"{k}: {v}" for k, v in response.headers.items()), encoding="utf-8"
    )
    (out / "http-status.txt").write_text(str(response.status_code), encoding="utf-8")
else:
    print(f"Reading saved response from {out}; no API call.")

if not (out / "http-status.txt").exists():
    raise SystemExit("Incomplete attempt. Keep the folder and check History before retrying.")
status = (out / "http-status.txt").read_text().strip()
if status != "200":
    raise SystemExit(f"HTTP {status}: inspect {out}/result.json and response-headers.txt")
try:
    data = json.loads((out / "result.json").read_bytes())
except ValueError:
    raise SystemExit("Invalid JSON; inspect the saved result.json")
request = json.loads((out / "request.json").read_bytes())
if not isinstance(data, dict) or data.get("source") != "youtube_captions" or data.get("status") != "done":
    raise SystemExit("Caption request did not finish successfully; inspect result.json")
tracks = data.get("results")
if not isinstance(tracks, list) or len(tracks) != 1 or not isinstance(tracks[0], dict):
    raise SystemExit("Expected one caption track; inspect result.json")
track = tracks[0]
language = request["params"]["language"]
allowed_languages = [language]
if request["params"]["auto"] and not language.endswith("-orig"):
    allowed_languages.append(language + "-orig")
if (track.get("videoId") != request["video_id"]
        or track.get("languageCode") not in allowed_languages
        or track.get("requestedLanguageCode", track.get("languageCode")) != language
        or track.get("isAutoGenerated") is not request["params"]["auto"]):
    raise SystemExit("Returned video, language or caption origin does not match the request")
if not isinstance(track.get("segments"), list):
    raise SystemExit("Expected a segments array; inspect result.json")
segments = []
for cue in track["segments"]:
    if not isinstance(cue, dict):
        raise SystemExit("Expected caption segment objects")
    start, end, text = cue.get("start"), cue.get("end"), cue.get("text")
    if (type(start) not in (int, float) or not math.isfinite(start) or start < 0
            or type(end) not in (int, float) or not math.isfinite(end) or end < start
            or not isinstance(text, str)):
        raise SystemExit("Invalid caption timing or text; inspect result.json")
    segments.append({**cue, "url": f"https://www.youtube.com/watch?v={track['videoId']}&t={math.floor(start)}s"})
captions = {**track, "segments": segments}
record = {"request": request, "requested_at": (out / "requested-at.txt").read_text().strip(),
          "usage": data.get("usage"), "segment_count": len(segments), "result_file": "result.json"}
for filename, value in (("captions.json", captions), ("record.json", record)):
    (out / filename).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Saved {len(segments)} segments to {out}/captions.json")
if not any(cue["text"].strip() for cue in segments):
    print("No caption text to cite. Keep the empty track and report the gap.")
在 timestamped-captions/ 中运行
python captions.py track-001

3. 读取带时间戳的文本

成功后输出 Saved N segments to track-001/captions.json。该文件保留返回的轨道,并为每个片段添加 URL。record.json 包含实际提交的请求、requested_at、用量和 segment_count;result.json 保留原始 API 响应。

本地读取 · 不调用 API
python -m json.tool track-001/captions.json
python -m json.tool track-001/record.json

输出示例

下方为精简的 captions.json 示意,实际文本及时间会不同。languageName 可能为 null;脚本保留该值。

timestamped-captions/track-001/captions.json
{
  "videoId": "FUfGcZ092b0",
  "languageCode": "en",
  "languageName": null,
  "isAutoGenerated": true,
  "segments": [
    {
      "start": 12.5,
      "end": 16.2,
      "text": "This is an illustrative caption segment.",
      "url": "https://www.youtube.com/watch?v=FUfGcZ092b0&t=12s"
    }
  ]
}

引用视频片段

输出前三个片段及其来源链接。start 和 end 保留以秒为单位的原始精度,仅 URL 开始时间向下取整:12.5 秒变为 &t=12s。片段顺序及重叠时间保持不变。

将 cite.py 保存到 captions.py 旁,再从同一文件夹运行。

timestamped-captions/cite.py
import json
from pathlib import Path

captions = json.loads(Path("track-001/captions.json").read_text(encoding="utf-8"))
for cue in captions["segments"][:3]:
    print(f"[{cue['start']}–{cue['end']}s] {cue['text']}")
    print(cue["url"])
    print()
从已保存字幕输出引用
python cite.py

保留字幕上下文

引用时以片段文本为依据;fullText 适合阅读,但无法定位具体片段。引用前检查相邻片段,尤其是自动字幕。保留 languageCode 和 isAutoGenerated,让应用或智能体能识别来源轨道。

复用已保存轨道

运行相同命令,可根据已保存响应重新生成 captions.json,无需密钥或新查询。编辑顶层 request.json 不会改变 track-001 中保存的请求。

本地复用
python captions.py track-001

选择其他轨道

要请求上传者提供的英文字幕,用下方版本替换 request.json,并使用 track-002。仅将 language 改为确实需要获取的代码,例如 en-orig 或 zh-Hans。元数据 transcriptLanguages 列出候选代码,不表示每个代码是否有自动或上传的轨道。

脚本要求 language 为单个字符串。语言数组使用另一种响应结构,包含 tracks 和各语言的 errors;该流程请参阅 API 参考。

timestamped-captions/request.json
{
  "source": "youtube_captions",
  "video_id": "FUfGcZ092b0",
  "params": {
    "language": "en",
    "auto": false
  }
}
新轨道 · 另一次 API 请求
python captions.py track-002

字幕缺失或不可用时

遇到的情况处理方法
所选轨道不可用检查视频、语言及 auto 选择。明确选择可用轨道;重复同一请求不会生成字幕。
segments: []已有轨道可能没有文本。脚本保存空轨道并提示缺口。不要将其编造成转写或摘要。
视频、语言或字幕来源不匹配不会写入 captions.json。使用文本前,对比保存的请求与 result.json。
时间无效或 segments 缺失检查 result.json。脚本会停止,不会编造时间戳或静默丢弃异常片段。
401 / 403 / 402分别检查密钥、youtube_captions 权限和余额,再发起新尝试。
429读取 response-headers.txt 中的 Retry-After 并等待。脚本不会自动重试。
超时、5xx、JSON 无效或文件夹不完整保留本次尝试,再次提交前检查请求历史。复用其文件夹不会发送新查询。

将 inspect_captions.py 保存到 captions.py 旁,再运行。

timestamped-captions/inspect_captions.py
from pathlib import Path

for name in ("http-status.txt", "response-headers.txt", "result.json"):
    path = Path("track-001") / name
    print(f"--- {name} ---")
    print(path.read_text(encoding="utf-8", errors="replace") if path.exists() else "Not saved")
本地检查
python inspect_captions.py