दस्तावेज़ देखें
उदाहरण
अपने पाठ, समय और भाषा के साथ मौजूदा YouTube कैप्शन ट्रैक को सेव करें। अपने ऐप या एजेंट के उत्तर में प्रशस्ति पत्रों के लिए प्रत्येक खंड के लिए एक वीडियो लिंक जोड़ें।
इस पेज पर
शुरू करने से पहले
youtube_captions अनुमति और उपलब्ध क्रेडिट के साथ एक कुंजी का उपयोग करें। Python 3.10+ को अनुरोधों के साथ चुनें, या Bash को cURL 7.76+ और jq के साथ चुनें। Windows पर, Git Bash का उपयोग Bash संस्करण के लिए किया जाता है।
1. वीडियो और कैप्शन ट्रैक चुनें
एक टाइमटाम्प्ड-कैप्शन फ़ोल्डर बनाएं और वहां request.json को बचायें। उस फ़ोल्डर में एक टर्मिनल खोलें। video_id को वीडियो के 11-character ID के साथ बदलें, इसके पूर्ण URL नहीं है।
यह उदाहरण अंग्रेजी स्वचालित कैप्शन का अनुरोध करता है। ऑटो = true के साथ, एन पहले en-orig की कोशिश करता है, फिर en। स्पष्ट -orig कोड और ऑटो = false सही रहते हैं। API स्वत: और अपलोडर प्रदान किए गए कैप्शन के बीच कभी स्विच नहीं करता है।
{
"source": "youtube_captions",
"video_id": "FUfGcZ092b0",
"params": {
"language": "en",
"auto": true
}
}2. कैप्शन को आकर्षित और सहेजना
एक संस्करण चुनें और अपनी स्क्रिप्ट को request.json के बगल में सहेजें। यह FLASHDATA_API_KEY पढ़ता है या एक छिपे हुए प्रॉम्प्ट पर अपनी कुंजी के लिए पूछता है। एजेंटों को अपने गुप्त स्टोर से उस पर्यावरण चर को लोड करना चाहिए।
ट्रैक-001 के साथ आउटपुट फ़ोल्डर के रूप में चलाएं। एक नया फ़ोल्डर एक क्वेरी भेजता है और इसकी सूचना के उपयोग को बचाता है। captions.json बनाने से पहले, स्क्रिप्ट लौटे हुए वीडियो ID, भाषा, कैप्शन मूल और सेगमेंट टाइमिंग को सत्यापित करती है।
python -m pip install requestsimport 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-001curl --version
jq --version#!/usr/bin/env bash
set -euo pipefail
out="${1:?Usage: bash captions.sh OUTPUT_FOLDER}"
if [[ ! -e "$out" ]]; then
jq -e '.source == "youtube_captions" and
(.video_id | if type == "string" then length == 11 and test("^[A-Za-z0-9_-]{11}$") else false end) and
(.params.language | if type == "string" then length > 0 and length <= 35 and
(test("[^A-Za-z0-9-]") | not) else false end) and
(.params.auto | type == "boolean")' request.json > /dev/null
if [[ -z "${FLASHDATA_API_KEY:-}" ]]; then
read -r -s -p "FlashData API key: " FLASHDATA_API_KEY
printf '\n'
fi
: "${FLASHDATA_API_KEY:?An API key is required}"
mkdir -- "$out"
cp request.json "$out/request.json"
date -u +'%Y-%m-%dT%H:%M:%SZ' > "$out/requested-at.txt"
curl --fail-with-body --silent --show-error --max-time 120 \
--request POST 'https://data.flashdata.dev/v1/queries/realtime' \
--header "X-API-Key: $FLASHDATA_API_KEY" \
--header 'Content-Type: application/json' --header 'Accept: application/json' \
--data-binary "@$out/request.json" \
--dump-header "$out/response-headers.txt" --output "$out/result.json" \
--write-out '%{http_code}' > "$out/http-status.txt" || {
printf 'Request failed. Keep %s and inspect its saved files before retrying.\n' "$out" >&2
exit 1
}
else
printf 'Reading saved response from %s; no API call.\n' "$out"
fi
if [[ ! -f "$out/http-status.txt" ]] || [[ "$(cat "$out/http-status.txt")" != 200 ]]; then
printf 'Incomplete or failed attempt. Inspect the saved files and History before retrying.\n' >&2
exit 1
fi
captions=$(jq -e --slurpfile request "$out/request.json" '
if .source != "youtube_captions" or .status != "done"
then error("Expected a successful youtube_captions response") else . end
| .results
| if type != "array" then error("Expected a results array")
elif length != 1 then error("Expected exactly one track") else .[0] end
| $request[0].params.language as $language
| if type != "object" then error("Expected a caption object")
elif .videoId != $request[0].video_id or (.requestedLanguageCode // .languageCode) != $language
or (.languageCode != $language and ($request[0].params.auto != true
or ($language | endswith("-orig")) or .languageCode != ($language + "-orig")))
or .isAutoGenerated != $request[0].params.auto
then error("Returned video, language or caption origin does not match the request") else . end
| if (.segments | type) != "array" then error("Expected a segments array") else . end
| .videoId as $id
| .segments |= map(
if type != "object" then error("Expected caption segment objects") else . end
| if (.start | type) != "number" or (.end | type) != "number" or (.text | type) != "string"
then error("Invalid caption timing or text")
elif (.start | isfinite | not) or (.end | isfinite | not) or .start < 0 or .end < .start
then error("Invalid caption timing")
else . + {url: ("https://www.youtube.com/watch?v=" + $id + "&t=" + (.start | floor | tostring) + "s")} end
)' "$out/result.json")
printf '%s\n' "$captions" > "$out/captions.json"
jq --slurpfile request "$out/request.json" --slurpfile captions "$out/captions.json" \
--arg requested_at "$(tr -d '\r\n' < "$out/requested-at.txt")" \
'{request: $request[0], requested_at: $requested_at, usage,
segment_count: ($captions[0].segments | length), result_file: "result.json"}' \
"$out/result.json" > "$out/record.json"
printf 'Saved %s segments to %s/captions.json\n' "$(jq '.segments | length' "$out/captions.json")" "$out"
if ! jq -e 'any(.segments[]; .text | test("\\S"))' "$out/captions.json" > /dev/null; then
printf 'No caption text to cite. Keep the empty track and report the gap.\n'
fi
bash captions.sh track-0013. Read the timetamped text
सफलता प्रिंट ने एन सेगमेंट को track-001/captions.json में सेव किया। यह फ़ाइल रिटर्न ट्रैक को संरक्षित करती है और प्रत्येक सेगमेंट में एक URL जोड़ती है। record.json में सटीक जमा अनुरोध, requested_at, उपयोग और segment_count; result.json मूल API प्रतिक्रिया रखता है।
python -m json.tool track-001/captions.json
python -m json.tool track-001/record.jsoncat track-001/captions.json
cat track-001/record.jsonउदाहरण
संक्षिप्त, स्पष्ट captions.json आपका पाठ और समय अलग होगा। languageName null हो सकता है; स्क्रिप्ट इसे इस तरह रखता है।
{
"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"
}
]
}एक वीडियो मार्ग उद्धृत करें
अपने स्रोत लिंक के साथ पहले तीन खंडों को प्रिंट करें। शुरू करें और अंत में अपने मूल परिशुद्धता के साथ सेकंड में रहें। केवल URL का प्रारंभ समय गोल हो गया है: 12.5 सेकंड और T=12 हो जाता है। सेगमेंट ऑर्डर और ओवरलैपिंग टाइमिंग को संरक्षित किया जाता है।
cite.py को captions.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.pyjq -r '.segments[:3][] |
"[\(.start)–\(.end)s] \(.text)\n\(.url)\n"' track-001/captions.jsonकैप्शन संदर्भ रखें
एक उद्धरण के लिए सबूत के रूप में खंड पाठ का उपयोग करें; fullText पढ़ने के लिए उपयोगी है, लेकिन एक मार्ग का पता नहीं है। उद्धरण से पहले आसपास के खंडों की जाँच करें, विशेष रूप से स्वचालित कैप्शन के लिए। languageCode और isAutoGenerated को बनाए रखें ताकि आपका ऐप या एजेंट सोर्स ट्रैक की पहचान कर सके।
बचाया ट्रैक का पुन: उपयोग करें
बचा हुआ जवाब से captions.json के पुनर्निर्माण के लिए उसी कमांड को चलाएं, बिना किसी कुंजी या नए क्वेरी के। शीर्ष स्तरीय request.json को संपादित करने से ट्रैक-001 के साथ संग्रहीत अनुरोध को नहीं बदलता है।
python captions.py track-001bash captions.sh track-001एक और ट्रैक चुनें
अपलोडर-provided अंग्रेजी कैप्शन का अनुरोध करने के लिए, इस संस्करण के साथ request.json को प्रतिस्थापित करें और ट्रैक-002 का उपयोग करें। केवल उन कोड के लिए भाषा बदलें जिन्हें आप पुनर्प्राप्त करने का इरादा रखते हैं, जैसे कि एन-ऑर्ग या zh-Hans। मेटाडाटा का transcriptLanguages उम्मीदवार कोड सूचीबद्ध करता है, नहीं कि प्रत्येक में एक स्वचालित या अपलोड ट्रैक है।
स्क्रिप्ट एक भाषा स्ट्रिंग की उम्मीद है। भाषा सरणी में ट्रैक और प्रति भाषा त्रुटियों के साथ एक अलग प्रतिक्रिया आकार होता है; उस वर्कफ़्लो के लिए API संदर्भ का उपयोग करें।
{
"source": "youtube_captions",
"video_id": "FUfGcZ092b0",
"params": {
"language": "en",
"auto": false
}
}python captions.py track-002bash captions.sh track-002अगर कैप्शन गायब हो जाते हैं या अनुपयोगी होते हैं
| क्या हुआ | क्या करें |
|---|---|
| चयनित ट्रैक अनुपलब्ध है | वीडियो, भाषा और ऑटो चयन की जाँच करें। एक उपलब्ध ट्रैक स्पष्ट रूप से चुनें; उसी अनुरोध को दोहराने से कैप्शन नहीं बनेंगे। |
| segments: [] | एक मौजूदा ट्रैक में कोई टेक्स्ट नहीं हो सकता है। स्क्रिप्ट खाली ट्रैक को बचाता है और अंतराल की रिपोर्ट करता है। इसे एक ट्रांसक्रिप्ट या सारांश में न बदलें। |
| गलत वीडियो, भाषा या कैप्शन मूल | No captions.json लिखा गया है। किसी भी टेक्स्ट का उपयोग करने से पहले result.json के साथ सहेजे गए अनुरोध की तुलना करें। |
| अमान्य समय या लापता खंड | निरीक्षण result.json स्क्रिप्ट का आविष्कार किए गए टाइमस्टैम्प्स को असाइन करने या चुपचाप खराब खंड को छोड़ने के बजाय बंद हो जाता है। |
| 401 / 403 / 402 | एक नए प्रयास से पहले, क्रमश: कुंजी, youtube_captions अनुमति और शेष राशि की जाँच करें। |
| 429 | Retry-After को response-headers.txt में पढ़ें और प्रतीक्षा करें। स्क्रिप्ट स्वचालित रूप से फिर से नहीं आती है। |
| टाइमआउट, 5xx, invalid JSON या एक अधूरा फ़ोल्डर | फिर से जमा करने से पहले प्रयास करें और History को चेक करें। इसके फ़ोल्डर का उपयोग कभी किसी अन्य क्वेरी को नहीं भेजता है। |
inspect_captions.py को 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.pyfor name in http-status.txt response-headers.txt result.json; do
printf '\n--- %s ---\n' "$name"
if [[ -f "track-001/$name" ]]; then cat "track-001/$name"; else printf 'Not saved\n'; fi
done