浏览文档
指南
为播放列表、阅读清单或应用数据集补全元数据,保留原始记录 ID 及每项处理结果。
本页内容
从原始记录到补全后的数据集
从引用两个视频的三条记录开始。每个不同视频仅查询一次,再将元数据关联回全部三条记录。本流程使用小型 Batch 请求,并保留未成功项。
| 输出字段 | 用途 |
|---|---|
| record_id · input | 按原顺序保留原记录及字段。 |
| video_id · query_index · job_id | 将每条记录追溯到对应查询。 |
| status · metadata · result_file | 已完成结果,或明确的待处理、失败、读取错误状态。 |
1. 检查工具及访问
将 FlashData CLI v1.2.1 加入 PATH,安装 Node.js 22+。在新目录中使用现有所有者凭据及 youtube_metadata 权限。下方命令适用于 Bash 与 PowerShell。
全程使用相同账户及配置档。命名配置请在终端设置 FLASHDATA_PROFILE,使收集脚本也使用该配置。智能体可从密钥存储加载 FLASHDATA_API_KEY。
flashdata --version
node --version
flashdata auth status --json
mkdir video-enrichment
cd video-enrichment检查余额及容量
确认所有者访问、youtube_metadata 权限,以及可容纳两项批量及待处理任务的容量。若仍在使用临时访问,请认领或使用单视频示例。提交前检查第 3 步的 dry-run 估价。
flashdata account balance --json
flashdata account limits --json2. 准备输入记录
保存为 videos.json,替换为你的记录 ID 及 11 字符 YouTube 视频 ID。其他字段保留在本地映射中,不发送给 FlashData。video_id 可重复,record_id 必须唯一。
[
{
"record_id": "lesson-intro",
"video_id": "jNQXAC9IVRw",
"collection": "Course"
},
{
"record_id": "playlist-song",
"video_id": "dQw4w9WgXcQ",
"collection": "Playlist"
},
{
"record_id": "saved-intro",
"video_id": "jNQXAC9IVRw",
"collection": "Reading list"
}
]保存 prepare.mjs
在 video-enrichment 目录中、videos.json 旁创建 prepare.mjs,复制下方完整代码并保存。
脚本先验证每行,再创建 prepared/。它为此元数据请求去重视频 ID,同时保留原记录及顺序。
// prepare.mjs — local preparation; sends no API requests.
import { mkdir, readFile, writeFile } from 'node:fs/promises';
const rows = JSON.parse((await readFile('videos.json', 'utf8')).replace(/^\uFEFF/, ''));
if (!Array.isArray(rows) || rows.length === 0) throw new Error('Supply a nonempty array of records.');
const recordIds = new Set(), videoIndexes = new Map(), queries = [];
const mapping = rows.map((input, index) => {
if (!input || typeof input !== 'object' || Array.isArray(input)
|| typeof input.record_id !== 'string' || !input.record_id.trim()
|| recordIds.has(input.record_id) || typeof input.video_id !== 'string'
|| !/^[A-Za-z0-9_-]{11}$/.test(input.video_id)) {
throw new Error('Invalid or duplicate record_id, or invalid video_id at row ' + (index + 1));
}
recordIds.add(input.record_id);
if (!videoIndexes.has(input.video_id)) {
videoIndexes.set(input.video_id, queries.length);
queries.push({ source: 'youtube_metadata', video_id: input.video_id,
params: { include_formats: false } });
}
return { input, query_index: videoIndexes.get(input.video_id) };
});
// Existing preparation is kept intact. Use it to resume, or choose a new folder.
await mkdir('prepared');
await writeFile('prepared/batch.json', JSON.stringify(queries, null, 2), { flag: 'wx' });
await writeFile('prepared/input-map.json', JSON.stringify(mapping, null, 2), { flag: 'wx' });
console.log(JSON.stringify({ inputRecords: rows.length, uniqueQueries: queries.length,
reusedVideoIds: rows.length - queries.length }, null, 2));在本地构建查询列表
保存 prepare.mjs 后运行一次。预期输出 inputRecords: 3、uniqueQueries: 2、reusedVideoIds: 1。本次运行保持 prepared/batch.json 及 prepared/input-map.json 不变。prepared/ 已存在时,复用它继续任务;不同数据集使用新目录。
node prepare.mjs3. 预览并提交去重后的视频
dry-run 检查实际查询数量、当前价格及账户限额。检查后仅提交一次。样例包含三条输入记录,但只有两项计费查询。
保留 submission.json 及 CLI 状态目录。中断后复用相同运行 ID 及输入。新运行 ID 会创建新工作;重试前先检查结果不确定的提交。
flashdata batch submit --input prepared/batch.json --dry-run --jsonflashdata batch submit --input prepared/batch.json --run-id video-metadata-001 --output submission.json --json4. 收集并关联结果
保存下方 collect.mjs 后运行。收集脚本对每个未完成任务最多等待两分钟,确认结果属于所请求视频,再将各项结果关联回原始记录。一次仅运行一个收集程序。
再次运行可继续读取同一批任务 ID。脚本复用已验证的本地结果,不发送新查询。退出码 1 表示仍有结果需要处理;先检查,不重新提交整个列表。
保存 collect.mjs
在同一 video-enrichment 目录中、submission.json 及 prepared/ 旁创建 collect.mjs,复制下方完整代码并保存。
// collect.mjs — reads saved jobs; never submits another query.
import { execFileSync } from 'node:child_process';
import { mkdir, readFile, writeFile, rename } from 'node:fs/promises';
const readJSON = async file => JSON.parse((await readFile(file, 'utf8')).replace(/^\uFEFF/, ''));
const cli = (...args) => JSON.parse(execFileSync('flashdata', [
...args, '--json', '--non-interactive', '--timeout', '2m',
], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024 }));
const inputs = await readJSON('prepared/batch.json');
const mapping = await readJSON('prepared/input-map.json');
const saved = await readJSON('submission.json');
const receipts = (saved.submission ?? saved).queries;
if (!Array.isArray(inputs) || !inputs.length || !Array.isArray(receipts)
|| receipts.length !== inputs.length || new Set(receipts.map(r => r.id)).size !== receipts.length
|| inputs.some(q => q.source !== 'youtube_metadata') || !Array.isArray(mapping) || !mapping.length
|| mapping.some(row => !Number.isInteger(row.query_index)
|| inputs[row.query_index]?.video_id !== row.input?.video_id)) {
throw new Error('Input/receipt mismatch. Keep the original prepared files and receipt.');
}
await mkdir('results', { recursive: true });
const binding = JSON.stringify({ inputs, mapping, receipts });
try { await writeFile('results/input-receipts.json', binding, { flag: 'wx' }); }
catch (error) {
if (error.code !== 'EEXIST') throw error;
if (await readFile('results/input-receipts.json', 'utf8') !== binding) {
throw new Error('Inputs or receipts changed. Restore the original files.');
}
}
const rows = inputs.map((input, query_index) => ({ query_index,
video_id: input.video_id, job_id: receipts[query_index].id, status: 'unread' }));
const saveRows = async (path, values) => {
await writeFile(path + '.next', values.map(row => JSON.stringify(row)).join('\n') + '\n');
await rename(path + '.next', path);
};
for (const row of rows) {
try {
if (!/^[a-zA-Z0-9_-]+$/.test(row.job_id ?? '')) throw new Error('Invalid job ID.');
const file = 'results/' + row.job_id + '.json';
let result;
try { result = await readJSON(file); }
catch (error) { if (error.code !== 'ENOENT') throw error; }
if (!result) {
let job;
try { job = cli('jobs', 'wait', row.job_id).data; }
catch { job = cli('jobs', 'get', row.job_id).data; }
if (job.videoId !== row.video_id || job.source !== 'youtube_metadata') {
throw new Error('Job/input mismatch. Inspect the saved input and receipt.');
}
row.status = job.status;
row.error = job.error ?? null;
if (job.status === 'completed') {
cli('jobs', 'result', row.job_id, '--output', file);
result = await readJSON(file);
}
}
if (result) {
if (result.status !== 'done' || result.source !== 'youtube_metadata'
|| result.results?.length !== 1 || result.results[0].videoId !== row.video_id) {
throw new Error('Result/video mismatch. Inspect the saved JSON before continuing.');
}
Object.assign(row, { status: 'completed', metadata: result.results[0], error: null,
credits: result.usage?.credits ?? null, result_file: file });
}
} catch (error) {
row.status = 'read_error';
row.error = error.stderr?.toString().trim() || error.message;
}
await saveRows('metadata.ndjson', rows); // One outcome and charge per unique query.
await saveRows('enriched.ndjson', mapping.map(({ input, query_index }) => {
const { credits, ...outcome } = rows[query_index]; // Do not duplicate a charge across input records.
return { record_id: input.record_id, input, ...outcome };
}));
}
const failed = rows.filter(row => ['failed', 'cancelled'].includes(row.status));
await writeFile('failed-videos.json', JSON.stringify(failed, null, 2));
console.table(rows.map(({ video_id, job_id, status }) => ({ video_id, job_id, status })));
console.log('Saved enriched.ndjson, metadata.ndjson and results/*.json.');
if (rows.some(row => row.status !== 'completed')) process.exitCode = 1;运行或继续收集脚本
保存 collect.mjs 后,在 video-enrichment 目录运行,并保留原 CLI 配置档和状态目录。
node collect.mjs预期文件
| 文件 | 用途 |
|---|---|
| enriched.ndjson | 每条原记录对应一行,包含重复视频及失败项。通过 record_id 导入。 |
| metadata.ndjson | 每项独立查询对应一行,含任务 ID、结果文件及实际 Credits。在此计算一次用量。 |
| results/*.json | 成功原始响应,以及保存的输入与回执绑定。 |
| failed-videos.json | 供检查的已确认失败或取消任务,不包含待处理及读取错误任务。 |
5. 在应用中使用补全后的记录
将 inspect.mjs 保存在 video-enrichment 目录中的 enriched.ndjson 旁,并在该目录运行。预期得到三条原记录及两项独立查询。通过 record_id 更新或插入完成行,保留 input 字段,并在导入报告中保留未完成行。从 metadata 读取标题及时长,使用 video_id 构建链接或后续字幕请求。
// inspect.mjs — inspect your dataset without another API call.
import { readFile } from 'node:fs/promises';
const rows = (await readFile('enriched.ndjson', 'utf8')).trim().split('\n').map(JSON.parse);
console.table(rows.map(row => ({ record_id: row.record_id, video_id: row.video_id,
collection: row.input.collection, status: row.status, title: row.metadata?.title ?? null })));
console.log('Original records:', rows.length);
console.log('Unique queries:', new Set(rows.map(row => row.query_index)).size);node inspect.mjs从需要处理的项目继续
在 24 小时保留期内保存结果。定期刷新时,仅在明确需要付费获取新数据时使用新快照目录及运行 ID;应用中的 record_id 保持稳定。
| 结果 | 下一步 |
|---|---|
| pending / processing | 稍后再次运行收集脚本,保持任务 ID 不变。 |
| failed / cancelled | 检查 failed-videos.json 及任务错误,修复原因后再明确重新请求该视频。 |
| read_error | 修复访问、输入绑定或已保存结果,保留原文件以供检查。读取错误不意味着需要新查询。 |
| 提交结果未知 | 再次提交前,检查本地运行记录及请求历史。 |
flashdata runs show video-metadata-001 --json