跳转到正文
中文
获取 API 密钥
浏览文档

指南

Bulk 文件处理

处理视频 ID 文件,获取全部结果分片,并在将数据集导入应用前检查覆盖情况。

本页内容

从 ID 文件到已检查的数据集

将此流程用于视频目录、研究集合或数据导入队列。一个文件使用同一来源,所有 ID 共用相同选项。先运行双视频元数据样例,再替换为自己的文件。

本流程生成的文件
video-ids.txt → Bulk 任务 → bulk-results.ndjson
  → audit/completed.ndjson       应用可用的结果
  → audit/failed-video-ids.txt   待检查的已确认失败项
  → audit/missing.ndjson        缺少结果的输入
  → audit/summary.json          覆盖情况及结果计数

开始前

安装 CLI,使用现有配置档或具有 youtube_metadata 权限的 FLASHDATA_API_KEY。确认 data.accessVerified: true,检查可用余额、两项请求价格及当前限额。自己的文件应按 ID 数量查询价格。每个被处理的 ID 是独立查询,不是整个文件统一计费。

第 1–3 步使用 Bash 与 jq,或 PowerShell 7。第 4 步的可选导入检查使用 Python 3.10+ 标准库。CLI 本身不依赖 Node.js 或 Python。

免费访问及账户检查
flashdata auth status --json
flashdata account balance --json
flashdata account pricing --source youtube_metadata --request-count 2
flashdata account limits

1. 准备 ID

在新的工作目录中运行。使用 UTF-8 文本,每行一个 11 字符视频 ID,不是 YouTube URL。文件最大 2 GiB。删除空行及重复项:CLI 会拒绝格式错误的输入,重复 ID 将分别处理。

Bash
# Run in a new working directory.
(
  set -euC
  printf '%s\n' 'jNQXAC9IVRw' 'dQw4w9WgXcQ' > video-ids.txt
)
cat video-ids.txt

2. 运行文件

CLI 创建任务、上传文件、启动处理,并将所有结果分片保存到一个 NDJSON 文件。使用新的输出路径。本地运行 ID bulk-first 会保存远程任务回执,供后续恢复。

Bash
flashdata bulk run --source youtube_metadata \
  --input video-ids.txt --run-id bulk-first \
  --output bulk-results.ndjson --timeout 30m --json

3. 检查结果

打开 bulk-results.ndjson。每行是包含 index、video_id 和 status 的 JSON 记录。成功行有 results 数组,失败行有 error。通过从零开始的 index 匹配输入,不依赖文件顺序。Bash 命令需要 jq。

一个成功行 · 简化示例
{"index":0,"video_id":"jNQXAC9IVRw","source":"youtube_metadata","status":"completed","results":[{"videoId":"jNQXAC9IVRw","title":"Example video title"}]}
Bash
# Bash + jq: read each record without loading the whole file.
jq -c '{index, video_id, status, title: .results[0].title, error}' bulk-results.ndjson

4. 导入前检查覆盖情况

保存下方 audit-bulk.py。使用未改变的输入文件及全部已获取结果运行。脚本检查各项 index、视频 ID 及来源,拒绝重复结果行,并区分已确认失败与缺失结果。其他来源请添加 --source SOURCE_ID。

成功样例应输出 inputRows: 2、completed: 2、failed: 0、missing: 0 及 allSucceeded: true。应用结果导入仅使用 completed 行,同时保留检查摘要及未成功项。

保存 audit-bulk.py

在工作目录中、video-ids.txt 和 bulk-results.ndjson 旁创建 audit-bulk.py,复制下方完整代码并保存。

脚本逐行读取文件,使用本地 SQLite 索引,无需将整个数据集加载到内存。输入须为经过验证的视频 ID 文件。每次检查使用新输出目录;解析完成前,部分文件单独保存。

audit-bulk.py
# audit-bulk.py — Python 3.10+, standard library only; no network requests.
import argparse
import json
import re
import sqlite3
import sys
from contextlib import ExitStack
from pathlib import Path

parser = argparse.ArgumentParser()
parser.add_argument('--input', required=True)
parser.add_argument('--results', required=True)
parser.add_argument('--out', required=True)
parser.add_argument('--source', default='youtube_metadata')
args = parser.parse_args()
out = Path(args.out)
try:
    out.mkdir()  # Keep any previous audit. Use a new directory for another attempt.
    with ExitStack() as stack:
        db = sqlite3.connect(out / 'index.sqlite')
        stack.callback(db.close)
        db.execute('CREATE TABLE inputs (idx INTEGER PRIMARY KEY, video_id TEXT, outcome TEXT)')
        count = 0
        with open(args.input, encoding='utf-8-sig') as inputs:
            for index, line in enumerate(inputs):
                video_id = line.strip()
                if not re.fullmatch(r'[A-Za-z0-9_-]{11}', video_id):
                    raise ValueError('Invalid ID on input line ' + str(index + 1))
                db.execute('INSERT INTO inputs VALUES (?, ?, NULL)', (index, video_id))
                count += 1
        if not count:
            raise ValueError('The input file is empty.')
        db.commit()
        files = {name: stack.enter_context(open(out / (name + '.part'), 'x', encoding='utf-8'))
                 for name in ['completed.ndjson', 'failed.ndjson', 'missing.ndjson', 'failed-video-ids.txt']}
        completed = failed = 0
        with open(args.results, encoding='utf-8-sig') as results:
            for line_number, line in enumerate(results, 1):
                if not line.strip():
                    continue
                row = json.loads(line)
                if not isinstance(row, dict) or type(row.get('index')) is not int:
                    raise ValueError('Invalid result index on line ' + str(line_number))
                expected = db.execute('SELECT video_id, outcome FROM inputs WHERE idx = ?',
                                      (row['index'],)).fetchone()
                if (not expected or row.get('video_id') != expected[0]
                        or row.get('source') != args.source or expected[1] is not None):
                    raise ValueError('Unknown, duplicate or mismatched result on line ' + str(line_number))
                status = row.get('status')
                if status not in ['completed', 'failed']:
                    raise ValueError('Unexpected item status on line ' + str(line_number))
                if status == 'completed':
                    if not isinstance(row.get('results'), list):
                        raise ValueError('Completed row is missing its results array.')
                    if args.source == 'youtube_metadata' and (len(row['results']) != 1
                            or not isinstance(row['results'][0], dict)
                            or row['results'][0].get('videoId') != expected[0]):
                        raise ValueError('Metadata does not belong to the requested video.')
                    completed += 1
                else:
                    failed += 1
                db.execute('UPDATE inputs SET outcome = ? WHERE idx = ?', (status, row['index']))
                files[status + '.ndjson'].write(json.dumps(row, ensure_ascii=False) + '\n')
        db.commit()
        missing = 0
        for index, video_id in db.execute('SELECT idx, video_id FROM inputs WHERE outcome IS NULL ORDER BY idx'):
            files['missing.ndjson'].write(json.dumps({'index': index, 'video_id': video_id,
                                                     'status': 'missing_result'}) + '\n')
            missing += 1
        for (video_id,) in db.execute("SELECT video_id FROM inputs WHERE outcome = 'failed' GROUP BY video_id ORDER BY MIN(idx)"):
            files['failed-video-ids.txt'].write(video_id + '\n')
        summary = {'source': args.source, 'inputRows': count, 'completed': completed,
                   'failed': failed, 'missing': missing, 'coverageComplete': missing == 0,
                   'allSucceeded': failed == 0 and missing == 0}
    for name in files:
        (out / (name + '.part')).rename(out / name)
    with open(out / 'summary.json', 'x', encoding='utf-8') as output:
        json.dump(summary, output, indent=2)
    print(json.dumps(summary, indent=2))
    sys.exit(0 if summary['allSucceeded'] else 2)
except Exception as error:
    print(str(error), file=sys.stderr)
    print('Audit not complete. Preserve this directory and inspect the inputs/results.', file=sys.stderr)
    sys.exit(1)

运行导入检查

在脚本、原始输入及已下载结果所在目录运行。此检查仅读取本地文件。

Bash
python3 audit-bulk.py --input video-ids.txt --results bulk-results.ndjson --out audit

导入完成行并保留检查结果

文件或信号使用方法
completed.ndjson通过 index 关联原始文件。目录可使用 video_id 作为主键;保存刷新历史时保留任务或快照标识。
failed.ndjson + failed-video-ids.txt明确重试这些 ID 前先检查错误。失败 ID 列表不包含成功项及缺失项。
missing.ndjson从已有任务恢复全部结果分片,再将恢复文件检查到新目录。缺失结果不等于已确认查询失败。
summary.jsoncoverageComplete 检查每项输入是否有结果;allSucceeded 还要求没有失败视频。失败或缺失都会使检查以退出码 2 结束。
退出码 1 / 无 summary.json数据格式错误或不匹配:检查已保存文件,不要将部分检查结果发布为完整数据集。

部分视频失败时

已完成的 Bulk 任务可能包含失败的视频。CLI 也会保存这些行,然后以 bulk_item_failures 退出。检查错误,再决定是否重试个别 ID;不要自动重提整个文件。

仅显示未成功的记录 · jq
jq -c 'select(.status != "completed") | {index, video_id, status, error}' bulk-results.ndjson

跟踪进度与容量

原命令运行期间可读取已保存的任务。CLI 将状态放在 data 下,直接 HTTP 放在 job 下。检查时使用延迟与退避,遇到 429 遵守 Retry-After。本地超时或关闭终端不会取消远程任务。

字段含义
input.scannedBytes / input.bytes文件扫描进度,不是查询完成度或媒体上传进度。
input.complete已读取全部输入;查询和结果打包可能仍在运行。
counts.accepted / completed / failed已提交 ID、成功视频和失败视频。未完成数 = accepted − completed − failed。
counts.invalid / results无效输入行 / 目前已打包的记录。HTTP 可接收包含无效行的文件;CLI 上传前会验证输入。
delivery客户数据交付:uploadedParts、retryCount、storageType 和 customerStorage,与每个视频的媒体上传分开。
Bash
(
set -eu
BULK_ID=$(flashdata runs show bulk-first --json | jq -er '.data.remoteId')
flashdata bulk get "$BULK_ID" --json
)

何时等待,何时处理

Bulk 按账户 maxPendingJobs 容量逐步提交,与其他任务共用容量。额度不足或订阅失效可能使任务暂停。恢复前检查 pauseReason。

状态下一步
awaiting_upload上传文件,然后启动已有任务。
running / finalizing等待。finalizing 可能仍在等待查询、打包及存储交付。
paused处理 pauseReason,恢复同一任务。
completed下载全部结果分片,检查失败行。
failed / cancelled检查 job.error 和已保存的回执。已接纳的工作可能继续完成;不发布已完成清单。

恢复中断的工作流

本地超时或结果下载中断后,恢复 bulk-first。这会读取已有远程任务,不重新提交数据集。使用新的输出文件名。partial_result 错误可能留下本地部分文件,请与恢复的结果分开保存。

全程使用相同的 CLI 配置和状态目录。使用命名配置时,为每条命令添加 --profile NAME。

情况处理
awaiting_uploadruns recover 不重放上传或启动。先检查已保存 ID、上传状态及原文件,再显式继续。
paused处理报告的问题,再以已保存 ID 执行 bulk resume。恢复命令不会自动恢复已暂停的任务。
401 / 403恢复提交账户与来源的有效访问权限。修复认证后复用同一任务。
409 / 410409:结果未就绪。410:存储结果已过期,请使用已保存副本。
上传 URL 过期确认旧任务从未启动后才创建新任务。提交结果不确定时,应先读取已保存 ID。
恢复已保存的运行
flashdata runs show bulk-first --json
flashdata runs recover bulk-first --output recovered-results.ndjson --timeout 30m --json

暂停或恢复任务

将 BULK_ID 替换为 runs show bulk-first 返回的 ID。暂停会停止新提交和结果打包;已接纳的查询继续。恢复前先解决 pauseReason。修改选项或存储凭据时,通过 Bulk API 更新已有任务。

暂停
flashdata bulk pause BULK_ID --json
处理原因后恢复
flashdata bulk resume BULK_ID --json

永久取消

仅在决定放弃任务时取消。取消不撤销已接纳查询,也不退还已完成工作的费用。计数可能继续变化,且不发布已完成清单。暂停是可恢复的。

取消指定任务
flashdata bulk cancel BULK_ID --json

获取全部结果分片

对于已完成的任务,CLI 根据清单将全部结果分片保存为一个 NDJSON 文件。使用新的输出路径,并对合并文件运行导入检查。Download 结果描述已交付媒体,不是 MP4 或音频字节。

获取已有任务的全部分片
flashdata bulk results BULK_ID --output saved-results.ndjson --timeout 30m --json

交付到你的存储

运行命令前,先在工作目录中将提供商凭据保存为 storage.json。使用下方链接的提供商字段,并将文件保密。CLI 的 --storage-config 读取此 JSON 文件,数据使用 result_storage,媒体使用 storage。--options 同样接收文件路径,不是内联 JSON。

使用已保存的存储配置运行

为元数据工作流添加存储
flashdata bulk run --source youtube_metadata --input video-ids.txt --storage-config storage.json --run-id bulk-with-storage --output stored-results.ndjson --timeout 30m --json