Chuyển đến nội dung
VI
Lấy khóa API
Duyệt tài liệu

Ví dụ

Làm giàu một tập tin của video IDs

Quay một YouTube ID Tập tin vào siêu dữ liệu JSON và CSVVới một kết quả trên một video. Dùng Python hay Bash với FlashData CLI.

Trên trang này

Trước khi bắt đầu

Dùng FlashData CLI v1.2.1 trên PATH, cộng Python 3.10+ (chỉ thư viện chuẩn) hay Bash có jq và OpenSSL. Cả hai phiên bản sử dụng các CLI vì đã tải lên, phục hồi công việc và thu hồi kết quả. Vào Windowssử dụng Git Bash cho Bash phiên bản.

Anh cần một người chủ. API phím với youtube_metadata Cho phép và tín dụng sẵn có. Dùng lại đăng nhập đã lưu của bạn, hoặc chạy auth login Một lần và nhập chìa khóa tại dấu nhắc ẩn của nó. Các tác nhân có thể cung cấp FLASHDATA_API_KEY từ cửa hàng bí mật của họ.

Những ví dụ này dùng giá trị mặc định CLI Thư mục hồ sơ và tiểu dụng. Hãy giữ lời tường thuật đó và lưu giữ tình trạng để hồi phục. Nếu auth status hiển thị truy cập tạm thời, yêu cầu trước khi khởi động Bulk.

Chỉ khi bạn không có đăng nhập đã lưu
flashdata auth login
Kiểm tra quyền truy cập và chi phí của hai-video ví dụ
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. Chuẩn bị video IDs

Tạo một thư mục làm giàu và lưu video-ids.txt ở đó. Mở một thiết bị cuối trong thư mục đó. Dùng một cái đi. 11- Hồ sơ. ID mỗi dòng, không có đầu đề, đường trống hoặc đầy đủ YouTube URLs.

Chọn một tập lệnh chuẩn bị và lưu nó bên cạnh video-ids.txt. Nó từ chối không hợp lệ và nhân bản IDsrồi lưu ảnh chụp nhập chuẩn, các tùy chọn siêu dữ liệu và chạy ID dưới prepared/. Thứ tự đầu vào được bảo quản.

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)
Chạy từ sự giàu có siêu lớn /
python prepare.py videos-001

Những gì đã được chuẩn bị

Trông mong được chuẩn bị 2 video độc nhất cho video001. Giữ sẵn sàng/không thay đổi. Siêu dữ liệu include_formats: false và include_chapters: false. Mỗi video được chấp nhận là một mục riêng biệt có thể thanh toán; các dòng trùng sẽ được xử lý riêng lẻ, vì vậy công thức này dừng lại trước khi gửi chúng.

Chạy đi ID Anh không dùng cho việc khác. Giữ lại các đoạn phim...001 cho nhiệm vụ này và hồi phục. Một cuộc chạy đua mới ID là cho một bộ dữ liệu mới có chủ đích hay mới.

2. Gửi và thu thập kết quả

Lưu process.py hay process.sh trong việc làm giàu trước khi làm. Hạt CLI tạo ra một Bulk công việc, tải lên những thứ đã chuẩn bị IDsbắt đầu xử lý và tiết kiệm tất cả kết quả phần vào bulk-results.ndjson. Sau đó thì địa phương dừng lại 30 phút; công việc máy phục vụ được chấp nhận tiếp tục.

Mỗi lần cố gắng nhận được thư mục riêng của mình theo nỗ lực/, với CLI @ info/ rich ready.txt chỉ ra kết quả mới nhất. Thoát 2 có nghĩa là kết quả hoàn chỉnh bao gồm các video bị hỏng; tiếp tục xuất khẩu và kiểm tra các hàng này.

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)
Xử lý tập tin đã chuẩn bị
python process.py submit

Kiểm tra tiến trình từ thiết bị cuối khác

Chạy khỏi sự giàu có lớn cùng một CLI tài khoản. Hành động trạng thái hiển thị người được lưu chạy và đọc từ xa Bulk công việc khi một ID có sẵn. Nó không tạo hay tiếp tục làm việc.

Đọc tiến trình hiện thời
python process.py status

3. Hòa giải và xuất

Lưu export.py hay export.sh Bên cạnh các kịch bản khác, sau đó chạy nó. Nó kiểm tra các chạy lưu lưu và đầu vào hah, sau đó phù hợp với tất cả kết quả bởi chỉ số zero và video_id. Các bộ phận có thể bị hỏng. Mất tích, nhân bản hoặc hàng không khớp ngăn chặn xuất khẩu.

Người xuất khẩu giữ lại đối tượng siêu dữ liệu đầy đủ, lỗi và thông báo sử dụng cho mỗi hàng. Các video không thành công vẫn còn hiển thị với metadata: null. Ví dụ nhỏ này nạp kết quả vào bộ nhớ; sử dụng việc kiểm tra hàng loạt trong Bulk xử lý tập tin cho một bộ dữ liệu lớn.

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)
Xuất ra vùng· no API cuộc gọi
python export.py

Dùng tập tin xuất

Thành công in các tập tin tóm tắt và lưu lại. Xuất ra 0 Khi tất cả các video thành công, 2 khi một số thất bại, hoặc 1 bị lỗi khi thẩm tra hay ghi. Một xuất khẩu/ được bảo tồn; hãy đọc nó tại địa phương thay vì phục tùng lại.

Tập tin dưới dạng xuất/Dùng nó đi
videos.jsonNhập vào ứng dụng hoặc dịch vụ của bạn. Hàng giữ thứ tự nhập, siêu dữ liệu, lỗi và sử dụng.
videos.csvXem lại tựa đề, thời gian và thất bại trong bảng tính. Văn bản giống như công thức được tiền tố bằng một sự teo; JSON giữ lại văn bản gốc.
summary.jsonKiểm tra tin tức và các completed/failed tính, liên kết đến chạy ID và Bulk ID.
failed-video-ids.txtXem lại chỉ xác nhận bị lỗi video trước khi quyết định yêu cầu trả tiền khác. Trống rỗng khi tất cả đều thành công.
Đọc bản tóm tắt và siêu dữ liệu đã lưu
python -m json.tool export/summary.json
python -m json.tool export/videos.json

Ví dụ kết quả với một video thất bại

Phần trích dẫn videos.json. Hoàn tất Bulk Công việc có thể chứa các video bị lỗi. Đừng xem một video bị lỗi là kết quả thành công trống hoặc thầm thả nó từ bộ dữ liệu của bạn.

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

Phục hồi cùng một công việc

Nếu không thể đọc được phần nào đó, hãy chạy đi để phục hồi. Nó thu thập công việc đã có vào một thư mục và cập nhật mới ready.txt Chỉ sau khi lấy lại hoàn toàn. Nó không tải lên hay gửi công việc thay thế. Sau đó chạy trình xuất khẩu nếu chưa được tạo ra.

Đã lưu kết quảHành động tiếp theo
bulk_item_failuresXuất và xem xét failed-video-ids.txt. Không phục hồi lại tất cả các video thành công.
partial_resultBảo tồn tập tin bộ phận. Phục hồi cùng một chạy để lấy lại tất cả các bộ phận trước khi xuất khẩu.
running / finalizingPhục hồi sau này sử dụng cùng một chạy ID, hồ sơ và thư mục tiểu dụng.
pausedĐọc pauseReason trong trạng thái, sửa chữa nguyên nhân, sau đó rõ ràng tiếp tục đó Bulk ID sử dụng hướng dẫn điều khiển.
awaiting_upload / bulk_input_requiredKiểm tra bản nháp đã lưu. Tải lên tập tin đã chuẩn bị gốc và khởi chạy những tập tin đã có Bulk ID; phục hồi không tua lại những hành động này.
Không chắc chắn phục tùng hoặc không từ xa IDGiữ cho chạy và kiểm tra lỗi đã lưu và Bulk Công việc trước khi thử lại. Một cuộc chạy đua mới ID có thể tạo ra một công việc khác.
Không đúng nguồn, hàng hay đầu vào bị thiếuKhông chấp nhận xuất khẩu. Kiểm tra ảnh chụp đã chuẩn bị, lưu chạy và tập tin kết quả; đừng phát minh ra siêu dữ liệu bị mất.
Kiểm tra, sau đó phục hồi công việc đã có
python process.py status
python process.py recover

Lưu hình ảnh này hoặc làm tươi nó cố ý

Lưu kết quả đã hoàn tất trong kết quả 24- ...để dành thời gian. Xuất khẩu tập tin cục bộ để tái sử dụng. Để nạp lại siêu dữ liệu sau, hãy dùng thư mục làm việc mới rồi chạy IDvà xem lại yêu cầu mới trước.