ドキュメントを探す
ガイド
オリジナルのレコードIDsとすべての結果を維持しながら、プレイリスト、読み取りリスト、アプリケーションデータセットにメタデータを追加します。
このページの内容
記録から豊かなデータセットまで
2つのビデオを参照する3つのレコードから始めましょう。 それぞれ異なるビデオを一度にクエリし、すべての3つのレコードにメタデータをバックアップします。 このワークフローでは、小さなBatchリクエストを使用し、不要なアイテムを目に見えるようにします。
| 出力フィールド | 目的: |
|---|---|
| record_id · input | オリジナル・レコード・フィールド、オリジナル・オーダー |
| video_id · query_index · job_id | 各レコードを生成したクエリにトレースします。 |
| status · metadata · result_file | 完了した結果、または明示的な pending/failed/read-error 結果。 |
1. ツールとアクセスをチェック
利用条件 FlashData CLI とりあえ1.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の許可と2つのバッチアイテムとジョブの保留のための部屋を確認します。 一時的なアクセスがまだ有効である場合は、それを主張するか、またはシングルビデオのレシピを使用します。 提出する前に、ドライランの見積もりをステップ3で確認します。
flashdata account balance --json
flashdata account limits --json2. 入力レコードの準備
これをvideos.jsonとして保存します。 自分のレコードIDsと11-character YouTubeのビデオIDsで値を置き換えます。 ローカルマッピングにフィールドを追加し、FlashDataに送信されていない。 繰り返しビデオ IDs が許可されます。 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
ビデオ強化フォルダ内のvideos.jsonの横にあるprepare.mjsを作成します。 下記のコードをコピーして保存します。
スクリプトは、prepared/.を作成する前に、すべての行を検証します 元のレコードと注文を保持しながら、このメタデータ要求のためにビデオIDsを複製します。
// 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 は、この実行のために変更されていません。 準備済み/ 既に存在している場合は、それを再開するために再利用します。異なるデータセットの新しいフォルダーを使用します。
node prepare.mjs3. プレビューして、ユニークな動画を投稿する
ドライランは、実際のクエリカウント、現在の価格設定、アカウントの制限をチェックします。 それを見直し、一度に提出してください。 サンプルには3つのレコードがあるにもかかわらず、2つの請求可能なクエリがあります。
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を以下に保存し、実行します。 コレクタは、未完成ジョブにつき最大2分待って、その結果が要求されたビデオに属し、元のレコードに各結果がそれぞれ参加することを検証します。 一度に1コレクターを実行します。
同じジョブIDsを再開するために再び実行します。 ローカルの結果を検証し、新しいクエリを送信しません。 終了コード 1 は、いくつかの結果がまだ注意を必要としていることを意味します。リストを返還するのではなく、それらを検査します。
保存 collect.mjs
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を保存した後、ビデオの充実から実行します。 元の CLI プロファイルとステートディレクトリをキープします。
node collect.mjs期待されるファイル
| ファイルファイル | 利用する |
|---|---|
| enriched.ndjson | 重複や失敗を含むオリジナルのレコードごとの1列。 record_idでインポートします。 |
| metadata.ndjson | ジョブID、結果ファイル、実際のクレジットを使用して、一列一意のクエリ。 一度に使用量をカウントします。 |
| results/*.json | 生の成功した応答と保存されたinput/receipt結合。 |
| failed-videos.json | 確認した failed/cancelled ジョブのレビュー このリストから、Pending と read-error ジョブが保持されます。 |
5. アプリケーションの豊富なレコードを使用する
enriched.ndjsonの横にあるビデオエンリッチメントでinspect.mjsを保存し、そのフォルダから実行します。 オリジナルの3つのレコードと2つのユニークなクエリを期待してください。 record_id で完了した行をアップサートし、入力フィールドを保持し、インポートレポートで不完全な行を目に見えるようにします。 タイトルと期間をメタデータから読みます。リンクや後キャプションのリクエストに 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-hour保持期間内に結果を保存します。 更新を再帰するためには、新しいスナップショットフォルダを使用し、新しいデータを支払いたい場合にのみIDを実行します。 アプリケーションでrecord_idを安定させます。
| アウトコンペ | 次のアクション |
|---|---|
| pending / processing | 後でコレクターを実行します。 IDsと同じジョブをキープします。 |
| failed / cancelled | failed-videos.jsonとジョブエラーを確認します。 意図的にその動画を再度要求する前に原因を修正します。 |
| read_error | アクセス、インプットバインディング、保存結果の修正。 未加工ファイルが検査のために保存します。 読み込みエラーは新しいクエリを必要としません。 |
| 投稿結果 未知 | ローカルランとHistoryを調べて、再度提出してください。 |
flashdata runs show video-metadata-001 --json