ข้ามไปยังเนื้อหา
TH
รับคีย์ API
เรียกดูเอกสาร

ตัวอย่าง

ดึงคำบรรยายพร้อมเวลา

บันทึกแทร็กคำบรรยาย YouTube ที่มีอยู่พร้อมข้อความ เวลา และภาษา เพิ่มลิงก์วิดีโอสำหรับแต่ละส่วนเพื่อใช้อ้างอิงในแอปหรือคำตอบของเอเจนต์

ในหน้านี้

ก่อนจะเริ่ม

ใช้ปุ่มพิมพ์ youtube_captions และเครดิตที่มีอยู่ เลือก Python 3.10+ ด้วยการร้องขอ หรือ Bash ด้วย cURL 7.76+ และ jq. เปิด Windowsใช้ Git Bash สําหรับ Bash เวอร์ชั่น

1. เลือกแทร็กวิดีโอและคําบรรยายภาพ

สร้างโฟลเดอร์เวลาประทับและบันทึก request.json ไว้ที่นี่ เปิดเทอร์มินัลในโฟลเดอร์นั้น แทนที่ video_id กับวีดีโอ 11- ช่างทําเล็บ IDไม่เต็ม URL.

ตัวอย่างนี้ต้องการคําบรรยายอัตโนมัติของอังกฤษ ด้วยอัตโนมัติ = true en-Arig ก่อน จากนั้น en explicit - รหัสออริกและอัตโนมัติ = false คงที่ API ไม่เคยสลับไปมาระหว่างคําบรรยายแบบอัตโนมัติกับตัวอัปโหลด

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

2. เรียกและบันทึกคําบรรยายภาพ

เลือกหนึ่งเวอร์ชันและบันทึกสคริปต์ของมันด้วย request.json มันอ่าน FLASHDATA_API_KEY หรือร้องขอกุญแจของคุณเมื่อมีสัญญาณลับ เจ้าหน้าที่ควรจะใส่ตัวแปร สิ่งแวดล้อมจากร้านลับของพวกเขา

ประมวลผลโดยใช้แทร็ก- 001 เป็นโฟลเดอร์ส่งออกเสียง โฟลเดอร์ใหม่จะส่งการสอบถามไปหนึ่งครั้ง และบันทึกการใช้งานของมันที่ได้รับรายงาน ก่อนที่จะสร้าง captions.jsonสคริปต์จะตรวจสอบวิดีโอที่ส่งกลับมา IDภาษา ที่มาของคําบรรยาย และช่วงเวลาต่าง ๆ

ติดตั้งในของคุณ Python สภาพแวดล้อมName
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. อ่านข้อความที่ถูกจับเวลาไว้

ลายนิ้วมือที่ประสบความสําเร็จได้ช่วย N parts ให้เหลือ track-001/captions.json. แฟ้มนั้นรักษาร่องเสียงที่ส่งกลับมาและเพิ่ม URL ในแต่ละส่วน record.json บรรจุคําร้องขอที่ส่งแล้ว requested_atการใช้งานและ segment_count; result.json คงภาพต้นฉบับไว้ API ตอบสนอง

อ่านค่า accessized_ no API เรียก
python -m json.tool track-001/captions.json
python -m json.tool track-001/record.json

ตัวอย่างผลลัพธ์

Abreview, contricive 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"
    }
  ]
}

Cite ข้อความวิดีโอ

พิมพ์ที่สามส่วนแรกด้วยที่อยู่เชื่อมโยงต้นทาง ให้เริ่มและจบการทํางานในหน่วยวินาทีด้วยความแม่นยําเดิม เฉพาะ URLเวลาเริ่มต้นถูกปัดลง: 12.5 วินาที=12เอส. การเรียงลําดับและเวลาทับกันถูกรักษาไว้

บันทึก 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 ด้วยรุ่นนี้และใช้แทร็ค002. เปลี่ยนภาษาเป็นรหัสที่คุณตั้งใจจะกู้มา เช่น เอนออร์ก หรือ แซช-ฮานส์ ข้อมูลกํากับภาพ transcriptLanguages มีรายชื่อรหัสผู้สมัคร ไม่ใช่ว่าแต่ละคนจะมีเพลงอัตโนมัติหรืออัปโหลด

สคริปต์ต้องการข้อความที่เป็นภาษาหนึ่ง อาร์เรย์ภาษามีรูปแบบการตอบสนองที่แตกต่างกัน โดยมีแทร็กเสียงและข้อผิดพลาดต่อช่อง; ใช้ API อ้างอิงถึงผลงานที่ไหลริน

timestamped-captions/request.json
{
  "source": "youtube_captions",
  "video_id": "FUfGcZ092b0",
  "params": {
    "language": "en",
    "auto": false
  }
}
เพลงใหม่_อื่น API ร้องขอ
python captions.py track-002

หากไม่มีคําบรรยายหรือไม่สามารถใช้ได้

เกิดอะไรขึ้นวิธีแก้ไข
ไม่มีแทร็กที่เลือกไว้โปรดตรวจสอบวิดีโอ, ภาษา และการเลือกอัตโนมัติ เลือกเพลงที่ใช้ได้โดยตรง การทําซ้ําตามที่ร้องขอมา จะไม่สามารถสร้างคําบรรยายภาพได้
segments: []แทร็กที่มีอยู่ไม่สามารถบรรจุข้อความได้ สคริปต์จะบันทึกเพลงที่ว่างอยู่ และแจ้งช่องว่าง อย่าเปลี่ยนมันเป็นสําเนาหรือสรุป
วิดีโอผิดภาษาหรือที่มาของคําบรรยายภาพNo captions.json ถูกเขียนขึ้น เปรียบเทียบการร้องขอที่บันทึกไว้กับ result.json ก่อนที่จะใช้ข้อความใด ๆ
เวลาหรือส่วนที่ขาดหายไปไม่ถูกต้องInspect result.json. สคริปต์ หยุด ลง แทน ที่ จะ กําหนด เวลา ที่ คิด ขึ้น มา หรือ ทํา ส่วน ที่ ไม่ ดี ให้ ตก ลง ไป อย่าง เงียบ ๆ.
401 / 403 / 402ดูที่กุญแจสิ youtube_captions ได้รับอนุญาตและความสมดุล ตามขั้นตอนก่อนที่จะพยายามใหม่
429อ่าน Retry-After ใน response-headers.txt และรอ. สคริปต์ไม่ได้ทําการลองใหม่โดยอัตโนมัติ
หมดเวลา, 5xx ใช้งานไม่ได้ JSON หรือโฟลเดอร์ที่ยังไม่สมบูรณ์ให้พยายามและตรวจสอบ History ก่อนการส่งข้อมูลอีกครั้ง การเรียกโฟลเดอร์ของมันกลับมา ไม่เคยส่งการถามอีก

บันทึก 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