コンテンツへスキップ
JA
APIキーを取得する
ドキュメントを探す

サンプル

タイムスタンプされたキャプションを取得する

テキスト、タイミング、言語で既存のYouTubeキャプショントラックを保存します。 アプリまたはエージェントの回答で引用のために、各セグメントにビデオリンクを追加します。

このページの内容

はじめる前に

youtube_captionsの許可と利用可能なクレジットでキーを使用してください。 Python 3.10+ とリクエスト、Bash と cURL 7.76+ と jq+ を選択します。 Windowsでは、BashバージョンのGit Bashを使用しています。

1. ビデオとキャプショントラックを選択します。

タイムスタンプされたキャプションフォルダを作成し、そこにrequest.jsonを保存します。 そのフォルダのターミナルを開きます。 video_idをビデオの11-character IDに置き換え、その完全なURLではありません。

この例では、英語自動キャプションをリクエストします。 auto=true を使って、 en は en-orig を最初に試みます、そして en を試みます。 Explicit -orig コードと auto=false は正確です。 API は、自動とアップロード機能のキャプションを切り替えることはありません。

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

2. カプションをフェッチして保存する

1つのバージョンを選択し、request.jsonの横にあるスクリプトを保存します。 FLASHDATA_API_KEY を読み込み、鍵を隠しプロンプトで要求します。 エージェントは、秘密ストアから環境変数を読み込む必要があります。

出力フォルダとしてtrack-001で実行します。 新規フォルダは1つのクエリを送信し、報告された使用量を保存します。 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.")
タイムスタンプキャプションから実行/
python captions.py track-001

3. タイムスタンプされたテキストを読む

track-001/captions.json.にN節を保存した成功プリント そのファイルは、返されたトラックを保存し、各セグメントに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"
    }
  ]
}

ビデオ通路をかき混ぜる

ソースリンクで最初の3つのセグメントをプリントします。 開始と終了は、元の精度で秒単位で滞在します。 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 の編集はトラック-001 と貯えられた要求を変えません。

ローカルで再利用する
python captions.py track-001

別のトラックを選択

リクエストが証明された英語のキャプションをアップロードするには、request.jsonをこのバージョンに置き換え、track-002を使用します。 en-orig や zh-Hans など、取得するコードにのみ言語を変更します。 MetadataのtranscriptLanguagesは、各人が自動またはアップロードされたトラックを持っているかどうかではなく、候補コードをリストします。

スクリプトは1つの言語文字列を期待します。 言語配列は、トラックと言語のエラーで異なる応答形状を持ちます。API リファレンスを使用して、そのワークフローに使用します。

timestamped-captions/request.json
{
  "source": "youtube_captions",
  "video_id": "FUfGcZ092b0",
  "params": {
    "language": "en",
    "auto": false
  }
}
新しいトラック・別のAPI要求
python captions.py track-002

キャプションが欠落しているか、または使用不能である場合

何が起こったのか対処方法
選択したトラックは利用できません。ビデオ、言語、自動選択をチェックします。 利用できるトラックを明示的に選んで下さい;同じ要求を繰り返すことはキャプションを作成しません。
segments: []既存のトラックはテキストを含んでいません。 スクリプトは空のトラックを保存し、ギャップを報告します。 トランスクリプトや要約に変えないでください。
間違ったビデオ、言語またはキャプションの起源captions.json は記述しません。 保存されたリクエストを result.json で比較して、任意のテキストを使用する前に.
無効なタイミングや欠落したセグメントresult.json を点検して下さい。 スクリプトは、発明されたタイムスタンプを割り当てたり、悪意のあるセグメントをサイレントにドロップしたりするのではなく、停止します。
401 / 403 / 402新しい試みの前に、キー、youtube_captionsのパーミッションと残高、それぞれを確認してください。
429response-headers.txt で Retry-After を読み、待ちます。 スクリプトは自動的に再試行しません。
タイムアウト、5xx、無効なJSON、または不完全なフォルダ再度提出する前に、Historyを試行して確認してください。 フォルダを再利用すると、別のクエリを送信しません。

captions.pyの横にあるinspect_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