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

ตัวอย่าง

เพิ่มข้อมูลให้ไฟล์ ID วิดีโอ

แปลงไฟล์ ID YouTube เป็น metadata แบบ JSON และ CSV โดยมีผลลัพธ์สำหรับแต่ละวิดีโอ ใช้ Python หรือ Bash ร่วมกับ FlashData CLI

ในหน้านี้

ก่อนจะเริ่ม

ใช้ FlashData CLI v1.2.1 บน PATH# บวก Python 3.10+ (ใช้เฉพาะไลบรารีมาตรฐานเท่านั้น), หรือ Bash ด้วย jq และ OpenSSL ทั้ง 2 รุ่นนี้ใช้ CLI เพื่ออัปโหลด, เรียกคืนงาน และรับส่วนผลลัพธ์ เปิด Windowsใช้ Git Bash สําหรับ Bash เวอร์ชั่น

คุณต้องการเจ้าของ API กุญแจพร้อม youtube_metadata ได้รับอนุญาตและเครดิตที่มีอยู่ ใช้การล็อกอินของเจ้าของที่บันทึกไว้ใหม่อีกครั้ง หรือเรียกทํางาน 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 ไว้ที่นั่น เปิดเทอร์มินัลในโฟลเดอร์นั้น ใช้หนึ่งตัว 11- ช่างทําเล็บ ID บรรทัดต่อบรรทัด, ไม่มีส่วนหัว, บรรทัดว่างหรือเต็ม YouTube URLs.

เลือกสคริปต์สําหรับเตรียมและบันทึกไว้ด้านข้าง video-ids.txt. มันปฏิเสธสิ่งที่ไม่ถูกต้องและซ้ําซ้อน IDsจัดเก็บค่าต่าง ๆ ในภาพ, ตัวเลือกข้อมูลกํากับภาพและการเรียกทํางาน 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)
ประมวลผลจากกลุ่มงานขนาดใหญ่/
python prepare.py videos-001

อะไรเตรียมพร้อม

คาด หมาย ว่า จะ ได้ รับ การ เตรียม พร้อม 2 วิดีโอที่พิเศษสําหรับวิดีโอ --001. ให้เตรียม/ ไม่เปลี่ยนแปลง ข้อมูลกํากับภาพที่ใช้ include_formats: false ถึง include_chapters: false. วีดีโอแต่ละอันที่ได้รับการยอมรับ เป็นรายการที่แยกได้ ซึ่งบรรทัดซ้ําจะถูกประมวลผลแยกกัน ดังนั้น สูตรนี้จะหยุดก่อนที่จะส่ง

ใช้ตัวประมวลผล ID คุณ ไม่ ได้ ใช้ เพื่อ ทํา งาน อื่น. Retain วิดีโอ- 001 สําหรับงานนี้และกู้คืนได้ ประมวลผลใหม่ ID สําหรับชุดข้อมูลหรือรีเฟรช

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. การส่งออกและส่งออก

บันทึก export.py หรือ export.sh นอกจากบทอื่น ๆ แล้วเรียกใช้มัน มันตรวจสอบการทํางานบันทึกและแฮดป้อนแล้วตรงกับทุกผลลัพธ์ที่ผ่านศูนย์ดัชนีและ 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)
ส่งออกเป็น HTML ภายในระบบ ไม่ใช่ API เรียก
python export.py

ใช้แฟ้มที่ส่งออก

ความสําเร็จจะพิมพ์ส่วนสรุปและบันทึกชื่อแฟ้ม ส่งออกออก 0 เมื่อทุกวิดีโอสําเร็จ 2 เมื่อบางอย่างล้มเหลว หรือ 1 เมื่อการตรวจสอบหรือการเขียนล้มเหลว เก็บค่าการส่งออก/ การส่งเมลที่มีอยู่แล้วไว้อ่านภายในเครื่อง แทนที่จะทําการส่งข้อมูลใหม่

แฟ้มภายใต้การส่งออก/ใช้มันเพื่อ
videos.jsonนําเข้าแอพฯ หรือเอเจ้นท์ของคุณ แถวเก็บลําดับการป้อนข้อมูล, ข้อมูลกํากับ, ข้อผิดพลาดและการใช้งาน
videos.csvชื่อหนังสือทบทวน ระยะเวลา และความล้มเหลวในตารางคํานวณ ข้อความคล้ายสูตรคือ apostrophe; JSON คงไว้ซึ่งข้อความต้นฉบับ
summary.jsonเช็คข่าวและ completed/failed นับแล้ว เชื่อมต่อกับการทํางาน ID ถึง Bulk ID.
failed-video-ids.txtการ ทบทวน เพียง แต่ ยืน ยัน ว่า ไม่ ประสบ ความ สําเร็จ ใน วี ดิ ทัศน์ ก่อน จะ ตัดสิน ใจ ขอ อีก อย่าง หนึ่ง. ว่างเปล่าเมื่อทั้งหมดประสบความสําเร็จ
อ่านส่วนสรุปและข้อมูลกํากับภาพที่บันทึกไว้
python -m json.tool export/summary.json
python -m json.tool export/videos.json

ผลลัพธ์ตัวอย่างกับวิดีโอที่ล้มเหลว

ภาพประกอบ 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_failuresส่งออกและทบทวนข้อมูล failed-video-ids.txt อย่าแทนที่วิดีโอที่ประสบความสําเร็จทั้งหมด
partial_resultรักษาแฟ้มบางส่วนไว้ เรียกคืนค่าเดิมเพื่อเรียกทุกส่วนก่อนการส่งออก
running / finalizingกู้คืนในภายหลังโดยใช้การทํางานเดียวกัน IDโปรไฟล์และไดเรกทอรีของรัฐ
pausedอ่าน pauseReason ในสถานะแก้ไขสาเหตุแล้วโดยตรงต่อว่า Bulk ID ใช้คู่มือควบคุม
awaiting_upload / bulk_input_requiredตรวจสอบฉบับร่างที่บันทึกไว้ อัปโหลดไฟล์ต้นฉบับที่เตรียมไว้แล้วเริ่ม Bulk ID เดิม ขั้นตอนกู้คืนจะไม่ทำการอัปโหลดหรือเริ่มงานซ้ำ
ไม่สามารถยืนยันการส่งหรือไม่มีระยะไกล IDให้ทํางานและตรวจสอบข้อผิดพลาดที่บันทึกไว้ Bulk งานก่อนที่จะลองใหม่ ประมวลผลใหม่ ID สามารถสร้างงานอื่นได้
แหล่งที่มาไม่ถูกต้อง, แถวที่ขาดหายไป หรือแฮชเข้ารูปแบบไม่ยอมรับการส่งออก Check loading parts, บันทึกการทํางานและผลลัพท์ไฟล์; ไม่ได้ประดิษฐ์ข้อมูลกํากับภาพหาย
โดย ผู้ เขียน ตื่น เถิด!
python process.py status
python process.py recover

บันทึกภาพที่จับได้นี้ หรือเรียกใหม่โดยเจตนา

บันทึกผลลัพธ์ที่เสร็จสมบูรณ์ภายใน 24- หน้าต่างสํารองชั่วโมง การส่งออกของคุณยังคงเก็บแฟ้มภายในระบบไว้สําหรับการใช้อีกครั้ง เพื่อรีเฟรชข้อมูลกํากับภาพในภายหลัง ให้ใช้โฟลเดอร์ที่ทํางานใหม่ และเรียก ID และทบทวนค่าใช้จ่ายที่ต้องการใหม่ก่อน