# YouTube 동영상 목록 풍부

기존의 기록 IDs 및 모든 결과를 유지하면서 재생 목록, 판독 목록 또는 애플리케이션 데이터 세트에 메타 데이터를 추가하십시오.

Canonical 참고: https://flashdata.dev/ko/docs/guides/enrich-youtube-videos
검토: 2026-11-05 FlashData

<a id="prepare"></a>

## 기록에서 enriched dataset에

2개의 동영상을 참조하는 3개의 레코드로 시작하십시오. Query 각 명백한 비디오 한 번, 다음 메타 데이터 다시 모든 세 개의 레코드에 가입. 이 워크플로우는 작은 Batch 요청을 사용하며 보이지 않는 아이템을 유지합니다.

| 산출 분야 | 제품정보 |
| --- | --- |
| record_id · input | 원래의 기록과 필드, 원래의 순서. |
| video_id · query_index · job_id | 각 레코드를 작성한 쿼리에 추적합니다. |
| status · metadata · result_file | 완료된 결과, 또는 명시된 pending/failed/read-error 결과. |

- [한 비디오 만](https://flashdata.dev/ko/docs/guides/video-metadata-recipe/reference.md)
- [더 큰 파일 처리](https://flashdata.dev/ko/docs/guides/bulk/reference.md)
- [Batch versus Bulk](https://flashdata.dev/ko/docs/reference/batch-and-bulk/reference.md#choose)

<a id="authenticate"></a>

## 1. 도구 및 접근

제품 정보 FlashData CLI ₢ 킹1.2.1 으로 PATH 으로 Node.js 22+. 기존 소유자 자격 증명 및 youtube_metadata 권한을 가진 새로운 폴더에서 실행하십시오. Bash와 PowerShell는 아래에 동일한 명령을 사용합니다.

계정과 프로필을 전체로 유지하십시오. 이름 프로필을 위해, 이 맨끝에 있는 FLASHDATA_PROFILE를 놓으십시오 그래서 수집가는 또한 그것을 사용합니다. 대리인은 그들의 비밀 상점에서 FLASHDATA_API_KEY를 적재할 수 있습니다.

### 도구 및 무료 액세스 체크

```bash
flashdata --version
node --version
flashdata auth status --json
mkdir video-enrichment
cd video-enrichment
```

- [CLI 설치](https://flashdata.dev/ko/docs/guides/flashdata-cli/reference.md#install)
- [소유자 키 구성](https://flashdata.dev/ko/docs/guides/cli-automation/reference.md#profiles)

<a id="access-check"></a>

### 균형과 수용량을 검사하십시오

소유자 액세스, youtube_metadata 권한 및 2 개의 배치 항목 및 종료 작업을 위한 방 확인. 임시 액세스가 여전히 활성화되면, 주장하거나 단일 비디오 요리법을 사용합니다. 제출하기 전에 단계 3에 건조 실행 견적을 검토하십시오.

#### 무료 계정 읽기

```bash
flashdata account balance --json
flashdata account limits --json
```


<a id="input"></a>

## 2. 입력 기록을 준비

videos.json로 저장하십시오. 자신의 레코드 IDs 및 11-character YouTube 비디오 IDs와 값을 교체하십시오. 로컬 매핑에 추가 필드가 유지되며 FlashData로 보내지 않습니다. 반복된 영상 IDs는 허용됩니다; record_id는 유일해야 합니다.

### videos.json

```json
[
  {
    "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"
  }
]
```


<a id="prepare-script"></a>

### 저장 prepare.mjs

비디오 엔리치먼트 폴더에서 videos.json 옆에 prepare.mjs를 만듭니다. 아래의 전체 코드를 복사하고 저장합니다.

스크립트는 prepared/.를 만들기 전에 모든 행을 유효 그것은 당신의 원본 기록 및 순서를 유지하면서 이 메타 데이터 요청을 위해 비디오 IDs를 deduplicates.

#### prepare.mjs

```javascript
// 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));
```


<a id="prepared"></a>

### 자주 묻는 질문 목록 만들기

prepare.mjs 저장 후 한 번 실행하십시오. inputRecords : 3, uniqueQueries : 2 및 reusedVideoIds : 1. prepared/batch.json 및 prepared/input-map.json를 유지하십시오. 준비/ 이미 존재하는 경우, 다시 이력서를 재사용; 다른 dataset에 대한 새로운 폴더를 사용합니다.

#### 준비 · API 통화 없음

```bash
node prepare.mjs
```


<a id="submit"></a>

## 3. 미리보기 및 독특한 동영상 제출

건조한 런은 실제 쿼리 수, 현재 가격 및 계정 제한을 확인합니다. 그것을 검토 한 다음 한 번 제출하십시오. 표본에는 입력이 3개의 기록이 있는더라도 2개의 청구 가능한 쿼리가 있습니다.

submission.json 및 CLI 상태 디렉토리를 유지하십시오. 동일한 실행 ID를 재사용하고 중단 후 입력합니다. 새로운 실행 ID는 새로운 일을 창조합니다; retrying의 앞에 불확실한 제출을 검열하십시오.

### 제출없이 미리보기

```bash
flashdata batch submit --input prepared/batch.json --dry-run --json
```

### 견적을 검토 한 후 제출

```bash
flashdata batch submit --input prepared/batch.json --run-id video-metadata-001 --output submission.json --json
```

- [Batch 요청 계약](https://flashdata.dev/ko/docs/reference/batch-and-bulk/reference.md#batch)

<a id="finish"></a>

## 4. 수집 및 가입

아래 collect.mjs를 저장하면 실행됩니다. 수집가가가가는 불확실한 일 당 2 분까지 기다리고, 그 결과가 요청한 비디오에 속하고, 원본 레코드에 각 결과를 결합합니다. 한 번에 수집가를 실행합니다.

동일한 직업 IDs를 다시 시작하십시오. 그것은 유효하게 한 현지 결과를 재사용하고 새로운 쿼리를 보낼 수 없습니다. 종료 코드 1는 몇 가지 결과가 여전히주의를 기울여야합니다. 목록의 재조정 대신 검사하십시오.


<a id="collector"></a>

### 저장 collect.mjs

submission.json 및 prepared/. 외에 동일한 비디오 엔리치먼트 폴더에서 collect.mjs를 생성 아래의 전체 코드를 복사하고 저장합니다.

#### collect.mjs

```javascript
// 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;
```


<a id="run-collector"></a>

### 수집가를 실행하거나 재시작

collect.mjs를 저장한 후에 영상 enrichment에서 뛰기. 원래 CLI 프로필 및 상태 디렉토리를 유지하십시오.

#### 수집 또는 재시작

```bash
node collect.mjs
```


<a id="output"></a>

### 예상된 파일

| 파일 | 사용하기 |
| --- | --- |
| enriched.ndjson | 원본 기록 당 1개의 줄, 중복과 실패를 포함하여. record_id로 가져 오기. |
| metadata.ndjson | ID, 결과 파일 및 실제 크레딧과 더불어 독특한 쿼리 당 한 줄. 한번의 사용량. |
| results/*.json | 저장된 input/receipt 바인딩 플러스 익지않는 성공적인 응답. |
| failed-videos.json | 확인 failed/cancelled 작업에 대한 리뷰. 자주 묻는 질문 |


<a id="use-dataset"></a>

## 5. 당신의 응용 프로그램에서 enriched 레코드를 사용하십시오

enriched.ndjson 외에 비디오 엔리치먼트에서 inspect.mjs를 저장하고 그 폴더에서 실행합니다. 3개의 원본 기록과 2개의 유일한 쿼리를 예상하십시오. record_id의 Upsert 완료된 행은 입력 필드를 유지하고, 수입 보고서에서 볼 수 없는 행을 유지합니다. metadata에서 제목과 기간을 읽으십시오; 링크 또는 나중에 캡션 요청을 위해 video_id를 사용하십시오.

### inspect.mjs

```javascript
// 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);
```

### 가입된 레코드를 검사

```bash
node inspect.mjs
```

- [비디오에 대한 captions를 선택하십시오](https://flashdata.dev/ko/docs/guides/youtube-data-guide/reference.md#captions)

<a id="recover"></a>

## 주의해야 하는 품목에서 계속

24-hour 보존 기간 내에 결과를 저장하십시오. 재순환을 위해 새로운 스냅샷 폴더를 사용하고 ID를 실행하면 신선한 데이터를 지불할 수 있습니다. record_id를 응용 프로그램에 안정적으로 유지하십시오.

| 결과 | 다음 작업 |
| --- | --- |
| pending / processing | 나중에 수집가를 실행합니다. 동일한 일을 지키십시오 IDs. |
| failed / cancelled | failed-videos.json 및 작업 오류를 검토하십시오. 의도적으로 그 비디오를 다시 요청하기 전에 원인을 수정합니다. |
| read_error | 액세스, 입력 바인딩 또는 저장된 결과를 수정합니다. 검사를 위한 원료 파일을 지키십시오; 읽힌 과실은 새로운 조회를 필요로 하지 않습니다. |
| 제출 outcome 알 수없는 | 다시 제출하기 전에 로컬 실행 및 History를 검사합니다. |

### 저장된 배치 검사

```bash
flashdata runs show video-metadata-001 --json
```

- [Recover uncertain 작업](https://flashdata.dev/ko/docs/guides/agent-recovery/reference.md)
- [Bulk로 더 큰 파일 처리](https://flashdata.dev/ko/docs/guides/bulk/reference.md)
- [저장 및 재사용 결과](https://flashdata.dev/ko/docs/guides/save-results/reference.md)
