İçeriğe geç
TR
API anahtarı al
Belgeleri incele

Örnekler

Erişim süreleri silinmiş

Mevcut bir YouTube serisini metin, zamanlama ve dil ile takip edin. Uygulamanızda veya ajanın cevabında alıntılar için her segmente bir video link ekleyin.

Bu sayfada

Başlamadan önce başlamadan önce

youtube_captions izni ve mevcut kredilerle bir anahtar kullanın. Python 3.10+ isteklerle veya Bash ile cURL 7.76+ ve jq+ ile. Onda Windows, kullanımı Git Bash Çünkü, Bash Versiyon.

1. Videoyu seçin ve takip et

Bir zamanlar silinmiş bir klasör oluşturun ve request.json'u orada kurtarın. O klasörde bir terminal açın. Değişimi Değiştir video_id Videonun ile 11-character IDAma onun tam anlamıyla değil URL.

Bu örnek İngilizce otomatik altyazıları talep eder. Auto=true ile, ilk önce en-orig'i deneyin, sonra en. Explicit -orig kodları ve auto=false tam olarak kalır. API asla otomatik ve yükleyici ayarlar arasında geçiş yapmaz.

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

2. Fetch ve komutları kurtar

Bir versiyon seçin ve senaryoyu request.json'nun yanında kurtarın. FLASHDATA_API_KEY'u okur veya anahtarınızı gizli bir şekilde sorar. Ajanslar bu ortamı gizli mağazalarından yüklenmelidir.

Run with track-001 as the print file. Yeni bir klasör bir sorgu gönderir ve bildirilen kullanımını kurtarır. captions.json yaratmadan önce, senaryo geri döndü videoyu ID, dil, profil zamanlamalarını doğrular.

Python ortamınıza yükleme
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.")
Zamanlar tarafından silinen-kaptions / Run from timestamped-captions /
python captions.py track-001

3. Zamanları silinmiş metinleri okuyun

Başarı baskıları track-001/captions.json. segmentlerine Kurtarıldı Bu dosya geri dönüş yolunu koruyor ve bir şeyler ekliyor URL Her segmente. record.json Kesin gönderilen istek içerir, requested_at, kullanımı ve segment_count; result.json Orijinali tutar API Cevap.

Yerel olarak okuyun · API arama
python -m json.tool track-001/captions.json
python -m json.tool track-001/record.json

Örnek çıktı

Abbreviated, illüstrasyonel captions.json. Metin ve zamanlamanız farklı olacaktır. languageName Olabilir olabilir olabilir null; senaryo bu şekilde tutar.

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"
    }
  ]
}

Bir video pasajı

İlk üç segmenti kaynak bağlantılarıyla yazdırın ve saniyeler içinde orijinal hassasiyetleriyle kalın. Sadece URL'un başlangıç zamanı yuvarlaktır: 12.5 saniyeler olur &t=12s. Segment siparişi ve zamanlaması korunmuştur.

cite.py'nun yanında tasarruf edin captions.py, o zaman aynı klasörden çalıştırın.

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()
Yazdır citations from save captions
python cite.py

Yönelme bağlamını tutun

Bir alıntı için kanıt olarak segment metni kullanın; fullText okumak için yararlıdır, ancak bir pasaj bulamaz. Segmentasyondan önce segmentleri kontrol edin, özellikle otomatik altyazılar için. Retain languageCode ve isAutoGenerated, böylece uygulamanız veya acenteniz kaynak takiplerini belirleyebilir.

Kurtarılan pisti yeniden kullanın

captions.json'u kaydedilen cevaptan yeniden inşa etmek için aynı komutu çalıştırın, anahtar veya yeni bir sorgu olmadan. En üst düzey request.json, takip eden isteki değiştirmez -001.

Yerel olarak yeniden kullanım
python captions.py track-001

Başka bir iz seçin

Yüklemek isteyen İngilizce altyazılarını talep etmek için, request.json'u bu sürümle değiştirin ve takip-002. Dil sadece koda, en-orig veya zh-Hans gibi almayı niyetle değiştirin. Metadata'nın transcriptLanguages, aday kodları listeliyor, her birinin otomatik veya yüklenmiş bir takip olup olmadığını değil.

Senaryo bir dil dizesini bekliyor. Dil dizileri parçaları ve dil hataları ile farklı bir yanıt şekline sahiptir; API referansını bu iş için kullanın.

timestamped-captions/request.json
{
  "source": "youtube_captions",
  "video_id": "FUfGcZ092b0",
  "params": {
    "language": "en",
    "auto": false
  }
}
Yeni takip · başka bir API isteği
python captions.py track-002

Eğer kuyruklar eksik veya güvenilmezse

Ne oldu?Yapılacak işlem
Seçilen takip mevcut değildirVideoyu, dili ve otomatik seçimi kontrol edin. Açık bir şekilde mevcut bir takip seçin; Aynı isteği tekrarlamak komutlar yaratmayacaktır.
segments: []Mevcut bir takip hiçbir metin içerebilir. Senaryo boş pisti kurtarır ve boşlukları rapor eder. Bunu bir transkript veya özet olarak çevirmeyin.
Yanlış video, dil veya satır kaynağıcaptions.json yazılır. Herhangi bir metin kullanmadan önce result.json ile kaydedilen istekle karşılaştırın.
Invalid zamanlamaları veya eksik segmentlerInspect result.json. Senaryo icat edilmiş zamanları atamak veya sessiz bir şekilde kötü bir segmenti terk etmek yerine durur.
401 / 403 / 402Anahtarı kontrol edin, youtube_captions izni ve dengesi, sırasıyla, yeni bir denemeden önce.
429Retry-After'de response-headers.txt'da okuyun ve bekleyin. Senaryo otomatik olarak yeniden denemez.
Timeout, 5xx, geçersiz JSON veya eksik bir klasörTekrar göndermeden önce History'u deneyin ve kontrol edin. klasörü yeniden kullanmak asla başka bir sorgu göndermez.

inspect_captions.py'un yanında captions.py'u kurtarın, sonra onu çalıştırın.

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")
Inspect yerel olarak
python inspect_captions.py