본문으로 건너뛰기
KO
API 키 받기
문서 둘러보기

예제

비디오 IDs의 파일을 풍부

YouTube ID 파일을 메타 데이터 JSON 및 CSV로 변환하여 비디오 당 1개의 결과가 있습니다. Python 또는 Bash를 FlashData CLI로 사용하십시오.

이 페이지의 내용

시작하기 전에

제품 정보 FlashData CLI ₢ 킹1.2.1 으로 PATH, 더하기 Python 3.10+ (표준 라이브러리 만), 또는 Bash 으로 jq 그리고 OpenSSL. 둘 다 버전은 올려주기를 위한 CLI를, 일 회복 및 결과 부품 retrieval 이용합니다. Windows에서 Git Bash를 Bash 버전으로 사용하십시오.

youtube_metadata 권한 및 사용 가능한 크레딧으로 소유자 API 키가 필요합니다. 저장된 소유자 로그인을 재사용하거나 auth login를 한 번 실행하고 숨겨진 프롬프트에서 키를 입력하십시오. 대리인은 그들의 비밀 상점에서 FLASHDATA_API_KEY를 공급할 수 있습니다.

이 예제는 기본 CLI 프로파일 및 상태 디렉토리를 사용합니다. 동일한 계정과 복구 상태 유지. auth status가 임시 접근을 보여주면 Bulk를 시작하기 전에 청구하십시오.

저장된 소유자 로그인이 없는 경우에만
flashdata auth login
이 두 비디오 예의 액세스 및 비용 확인
flashdata --version
flashdata auth status --json
flashdata account balance --json
flashdata account pricing --source youtube_metadata --request-count 2 --json
flashdata account limits --json

1. 비디오 IDs 준비

대량 보유 폴더를 만들고 video-ids.txt를 저장할 수 있습니다. 그 폴더에 터미널을 엽니다. 선 당 1 11-character ID를, 머리 없이, 공백 선 또는 가득 차있는 YouTube URLs 사용하십시오.

한 준비 스크립트를 선택하고 video-ids.txt 옆에 저장하십시오. 그것은 잘못된 및 중복을 거부 IDs, 그 후에 정상적인 입력 snapshot, metadata 선택권 및 뛰기 저장하십시오 ID 이름 * prepared/. 입력 순서는 보존됩니다.

bulk-enrichment/video-ids.txt
jNQXAC9IVRw
dQw4w9WgXcQ
bulk-enrichment/prepare.py
# Save as bulk-enrichment/prepare.py. Python 3.10+, standard library only.
import hashlib
import json
import os
import re
import sys
from pathlib import Path
from subprocess import run, CalledProcessError, DEVNULL

ROOT = Path(__file__).resolve().parent
try:
    os.umask(0o077)
    run_id = sys.argv[1]
    if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.:@+-]{0,159}", run_id):
        raise ValueError("Choose a valid, stable run ID.")
    ids = (ROOT / "video-ids.txt").read_text(encoding="utf-8-sig").splitlines()
    ids = [line.strip() for line in ids]
    if not ids or any(not re.fullmatch(r"[A-Za-z0-9_-]{11}", value) for value in ids):
        raise ValueError("Use one 11-character video ID per line, with no blank rows or URLs.")
    if len(set(ids)) != len(ids):
        raise ValueError("Remove duplicate IDs before submitting; they would be processed separately.")
    data = ("\n".join(ids) + "\n").encode("utf-8")
    prepared = ROOT / "prepared"
    prepared.mkdir(mode=0o700)  # Refuse to overwrite an existing input snapshot.
    (prepared / "video-ids.txt").write_bytes(data)
    (prepared / "options.json").write_text(json.dumps({
        "include_formats": False, "include_chapters": False,
    }, indent=2), encoding="utf-8")
    if os.name == "nt":
        # The CLI requires a private options file, including on Windows.
        command = """
$ErrorActionPreference = 'Stop'
$path = [System.IO.Path]::GetFullPath("./prepared/options.json")
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
$acl = [System.Security.AccessControl.FileSecurity]::new()
$acl.SetAccessRuleProtection($true, $false)
$acl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new($user, 'FullControl', 'Allow'))
[System.IO.File]::SetAccessControl($path, $acl)
"""
        run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", command],
            cwd=ROOT, stdin=DEVNULL, check=True, capture_output=True)
    plan = {"run_id": run_id, "source": "youtube_metadata", "input_count": len(ids),
            "input_sha256": hashlib.sha256(data).hexdigest()}
    (prepared / "plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8")
    print("Prepared", len(ids), "unique videos for", run_id)
except (IndexError, OSError, ValueError, CalledProcessError) as error:
    print(str(error), file=sys.stderr)
    sys.exit(1)
Bulk-enrichment/에서 실행
python prepare.py videos-001

준비하는 것

예상 준비 2 독특한 동영상에 대한 비디오-001. 준비/변경되지 않음 메타데이터는 include_formats: false와 include_chapters: false를 사용합니다. 각 허용 된 비디오는 별도의 청구 가능한 항목입니다. 중복 라인은 별도로 처리되므로이 레시피는 제출하기 전에 중지합니다.

다른 작업에 사용되지 않은 실행 ID를 사용하십시오. 이 작업의 저장소 및 복구에 대한 비디오-001를 유지합니다. 새로운 실행 ID는 의도적인 새로운 dataset 또는 새로 고침을 위해 입니다.

2. 제출 및 결과 수집

저장 process.py 또는 process.sh 대량 에너지에 그것을 실행하기 전에. CLI는 한 Bulk 일을 만들고, 준비된 IDs를 업로드하고, bulk-results.ndjson로 각 결과를 가공하고 저장합니다. 로컬 대기는 30 분 후에 중지합니다; 받아들인 서버는 계속 작동합니다.

각 시도는 CLI 영수증, 오류 및 저장된 실행과 함께 시도 / 아래 자체 폴더를 가져옵니다. ready.txt 포인트 최신 전체 결과. 종료 2는 완전한 결과를 포함합니다 실패한 영상을 의미합니다; 수출하고 그 줄을 검열하기 위하여 계속하십시오.

bulk-enrichment/process.py
# Save as bulk-enrichment/process.py. Requires the FlashData CLI on PATH.
import hashlib
import json
import os
import sys
import tempfile
from pathlib import Path
from subprocess import run, DEVNULL

ROOT = Path(__file__).resolve().parent


def read_json(path):
    return json.loads(path.read_text(encoding="utf-8"))


def main(action):
    os.umask(0o077)
    plan = read_json(ROOT / "prepared/plan.json")
    ids = ROOT / "prepared/video-ids.txt"
    if hashlib.sha256(ids.read_bytes()).hexdigest() != plan["input_sha256"]:
        raise ValueError("The prepared input changed. Restore it before recovery.")
    # Use the same default profile and state directory as auth login/status.
    flags = ["--json", "--non-interactive"]
    def cli(*args):
        return run(["flashdata", *args, *flags], cwd=ROOT, stdin=DEVNULL,
                   capture_output=True, text=True, encoding="utf-8")
    if action == "status":
        result = cli("runs", "show", plan["run_id"])
        if result.returncode:
            raise ValueError(result.stderr)
        saved = json.loads(result.stdout)["data"]
        print(json.dumps({k: saved.get(k) for k in
                          ("id", "remoteId", "status", "stage", "errorCode")}, indent=2))
        if saved.get("remoteId"):
            result = cli("bulk", "get", saved["remoteId"])
            print(result.stdout or result.stderr)
            return result.returncode
        return 0
    if action not in ("submit", "recover"):
        raise ValueError("Choose submit, status or recover.")
    attempts = ROOT / "attempts"
    attempts.mkdir(exist_ok=True)
    directory = Path(tempfile.mkdtemp(prefix="run-", dir=attempts))
    output = str(directory / "bulk-results.ndjson")
    if action == "submit":
        args = ["bulk", "run", "--source", plan["source"], "--input", str(ids),
                "--options", str(ROOT / "prepared/options.json"), "--run-id", plan["run_id"]]
    else:
        args = ["runs", "recover", plan["run_id"]]
    result = cli(*args, "--output", output, "--timeout", "30m")
    (directory / "receipt.json").write_text(result.stdout, encoding="utf-8")
    (directory / "error.json").write_text(result.stderr, encoding="utf-8")
    (directory / "exit-code.txt").write_text(str(result.returncode))
    print("Attempt:", directory.relative_to(ROOT))
    # bulk_item_failures still includes a complete result file with failed rows.
    code = json.loads(result.stderr).get("error", {}).get("code") if result.stderr.strip() else None
    if result.returncode and code != "bulk_item_failures":
        raise ValueError("Collection stopped. Inspect error.json; recover the same run.")
    saved = cli("runs", "show", plan["run_id"])
    (directory / "run.json").write_text(saved.stdout, encoding="utf-8")
    if saved.returncode or not Path(output).is_file():
        raise ValueError("Could not save the run record and results together.")
    record = json.loads(saved.stdout)
    data = record.get("data", {})
    if (not record.get("ok") or data.get("status") != "succeeded"
            or data.get("id") != plan["run_id"] or data.get("source") != plan["source"]
            or data.get("inputFileHash") != plan["input_sha256"]):
        raise ValueError("Inspect the run/input binding before exporting.")
    pointer = ROOT / "ready.next"
    pointer.write_text(directory.relative_to(ROOT).as_posix(), encoding="utf-8")
    pointer.replace(ROOT / "ready.txt")
    print("Results ready for export." if code is None else "Results ready; inspect failed video rows.")
    return 2 if code == "bulk_item_failures" else 0


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1]))
    except (IndexError, KeyError, OSError, ValueError) as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
준비된 파일 처리
python process.py submit

다른 맨끝에서 진행을 검사하십시오

같은 CLI 계정으로 대량의 유지를 실행합니다. 상태 동작은 저장된 실행을 보여 주며 Bulk 작업을 읽습니다. ID는 사용할 수 있습니다. 그것은 만들거나 재시작하지 않습니다.

현재 진행 상황을 읽으십시오
python process.py status

3. Reconcile와 수출

다른 스크립트 옆에 export.py 또는 export.sh를 저장하고, 그 다음 실행하십시오. 저장된 실행 및 입력 해시를 확인하고, 0기반 색인 및 video_id에 의해 모든 결과를 일치시킵니다. 결과 부품은 주문 중 도착 할 수 있습니다. 미스링, 중복 또는 무 일치 행은 수출을 중지합니다.

수출업자는 전체 메타데이터 객체, 오류 및 각 행에 대한 사용 보고를 유지합니다. 실패한 동영상은 metadata: null로 볼 수 있습니다. 이 작은 예제는 메모리로 결과를로드합니다. 큰 데이터 세트에 대한 Bulk 파일 처리의 스트리밍 감사를 사용합니다.

bulk-enrichment/export.py
# Save as bulk-enrichment/export.py. Local files only; no API calls.
import csv
import hashlib
import json
import os
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent
try:
    os.umask(0o077)
    directory = (ROOT / "ready.txt").read_text(encoding="utf-8").strip()
    if not re.fullmatch(r"attempts/run-[A-Za-z0-9_-]+", directory):
        raise ValueError("Use the ready.txt written by process.py or process.sh.")
    directory = ROOT / directory
    def read_json(path):
        return json.loads(path.read_text(encoding="utf-8"))
    plan = read_json(ROOT / "prepared/plan.json")
    raw = (ROOT / "prepared/video-ids.txt").read_bytes()
    ids = raw.decode("utf-8").splitlines()
    saved = read_json(directory / "run.json")
    run = saved["data"]
    digest = hashlib.sha256(raw).hexdigest()
    if (not saved.get("ok") or run.get("status") != "succeeded" or run.get("kind") != "bulk:run"
            or run.get("id") != plan["run_id"] or run.get("source") != "youtube_metadata"
            or run.get("inputFileHash") != digest or plan["input_sha256"] != digest
            or plan["input_count"] != len(ids) or not run.get("remoteId")):
        raise ValueError("The saved run does not match this input file.")
    # This recipe loads a small file into memory to validate it before writing exports.
    records = {}
    with (directory / "bulk-results.ndjson").open(encoding="utf-8") as source:
        for line in source:
            row = json.loads(line)
            index = row.get("index")
            if (type(index) is not int or not 0 <= index < len(ids) or index in records
                    or row.get("video_id") != ids[index] or row.get("source") != "youtube_metadata"
                    or row.get("status") not in ("completed", "failed")):
                raise ValueError("Unknown, duplicate or mismatched result row.")
            metadata = None
            if row["status"] == "completed":
                results = row.get("results")
                if (not isinstance(results, list) or len(results) != 1
                        or not isinstance(results[0], dict) or results[0].get("videoId") != ids[index]):
                    raise ValueError("Completed metadata does not match its video.")
                metadata = results[0]
            records[index] = {
                "index": index, "video_id": ids[index], "status": row["status"],
                "metadata": metadata, "error": row.get("error"), "usage": row.get("usage"),
            }
    if len(records) != len(ids):
        raise ValueError("Missing result rows. Recover the same run before exporting.")
    videos = [records[index] for index in range(len(ids))]
    failed = [v["video_id"] for v in videos if v["status"] == "failed"]
    output = ROOT / "export"
    output.mkdir(mode=0o700)  # Never overwrite an earlier export.
    (output / "videos.json").write_text(json.dumps(videos, ensure_ascii=False, indent=2), encoding="utf-8")
    def cell(value):
        if value is None:
            return ""
        if not isinstance(value, str):
            value = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
        # Keep remote text from being interpreted as a spreadsheet formula.
        return "'" + value if re.match(r"^[ \t\r\n]*[=+@-]|^[\t\r\n]", value) else value
    with (output / "videos.csv").open("x", encoding="utf-8", newline="") as target:
        writer = csv.writer(target)
        writer.writerow(["index", "video_id", "status", "title", "duration", "error"])
        for video in videos:
            metadata = video["metadata"] or {}
            writer.writerow([cell(v) for v in (video["index"], video["video_id"], video["status"],
                            metadata.get("title"), metadata.get("duration"), video["error"])])
    (output / "failed-video-ids.txt").write_bytes("".join(v + "\n" for v in failed).encode("utf-8"))
    summary = {"run_id": plan["run_id"], "bulk_id": run["remoteId"], "input_count": len(ids),
               "completed": len(ids) - len(failed), "failed": len(failed), "coverage_complete": True}
    (output / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print(json.dumps(summary, indent=2))
    print("Saved export/videos.json, videos.csv and failed-video-ids.txt")
    sys.exit(2 if failed else 0)
except (OSError, ValueError, KeyError, TypeError) as error:
    print(str(error), file=sys.stderr)
    sys.exit(1)
로컬로 내보내기 · API 통화 없음
python export.py

수출된 파일을 사용하십시오

성공은 요약 및 저장된 파일 이름을 인쇄합니다. 0를 내보내면 모든 비디오가 성공할 때 2를 종료하거나 유효성 검사 또는 쓰기가 실패할 때 1를 종료합니다. 기존의 수출 / 보존; rerunning 제출 대신 로컬로 읽으십시오.

수출/의 밑에 파일사용하기
videos.json앱 또는 에이전트 워크플로우로 가져 오기. Rows는 입력 순서, metadata, 과실 및 사용법을 지킵니다.
videos.csv스프레드 시트의 제목, 기간 및 실패를 검토하십시오. 공식 같은 텍스트는 apostrophe로 접힙니다; JSON는 원본 텍스트를 유지합니다.
summary.jsonID 및 Bulk ID와 연결되는 범위와 completed/failed 조사를 검사하십시오.
failed-video-ids.txt다른 유료 요청에 따라 결정하기 전에 만 확인 된 실패한 비디오를 검토하십시오. 모두 성공할 때 빈.
저장된 요약과 metadata를 읽으십시오
python -m json.tool export/summary.json
python -m json.tool export/videos.json

실패한 영상을 가진 outcome 보기

일러스트 videos.json 발췌. 완료된 Bulk 작업은 실패한 동영상을 포함할 수 있습니다. 실패한 비디오를 빈 성공적인 결과로 치료하지 않거나 조용히 데이터셋에서 떨어지지 마십시오.

export/videos.json
[
  {
    "index": 0,
    "video_id": "jNQXAC9IVRw",
    "status": "completed",
    "metadata": {
      "videoId": "jNQXAC9IVRw",
      "title": "Example video",
      "duration": 19
    },
    "error": null,
    "usage": null
  },
  {
    "index": 1,
    "video_id": "dQw4w9WgXcQ",
    "status": "failed",
    "metadata": null,
    "error": {
      "code": "example_video_unavailable"
    },
    "usage": null
  }
]

같은 일을 복구

대기 중지 또는 결과 부품이 읽을 수 없다면 복구를 실행하십시오. 기존의 작업을 신선한 시도 폴더로 수집하고 ready.txt를 업데이트합니다. 그것은 업로드하거나 교체 작업을 제출하지 않습니다. 그런 다음 수출업자를 실행하십시오. 수출 / 아직 생성되지 않았습니다.

관련 상품다음 작업
bulk_item_failuresfailed-video-ids.txt의 수출 및 검토. 모든 성공적인 비디오를 resubmit하지 마십시오.
partial_result부분적인 파일을 보존합니다. 수출하기 전에 모든 부품을 검색하는 것과 동일한 실행을 복구합니다.
running / finalizingID, 프로파일 및 상태 디렉토리를 사용하여 나중에 복구하십시오.
paused상태에 pauseReason를 읽으십시오, 원인을 고치고, 그 후에 통제 가이드를 사용하여 Bulk ID가 그 것을 명시적으로 재개합니다.
awaiting_upload / bulk_input_required저장된 초안을 검사합니다. 원래 준비 파일을 업로드하고 기존 Bulk ID를 시작하십시오. 복구는 이러한 작업을 재생하지 않습니다.
제출 또는 원격 ID 없음실행을 유지 하 고 저장 된 오류 및 Bulk 작업 복원 하기 전에. 새로운 실행 ID 다른 일을 만들 수 있습니다.
잘못된 소스, 누락된 행 또는 입력 해시 mismatch수출은 받아들여지지 않습니다. 준비된 스냅샷, 저장된 실행 및 결과 파일 확인; 누락 된 메타데이터를 사용하지 마십시오.
검사, 그 후 기존의 작업을 복구
python process.py status
python process.py recover

이 스냅 샷을 저장하거나 그것을 deliberately

24-hour 보존 창 내의 완료된 결과를 저장합니다. 귀하의 수출은 재사용을위한 로컬 파일 남아있다. metadata를 나중에 새로 고침하려면 새로운 작업 폴더를 사용하고 ID를 실행하고 새로운 요청 비용을 먼저 검토하십시오.