# 타임스탬프 캡션 검색

기존의 YouTube 캡션 트랙을 텍스트, 타이밍 및 언어로 저장하십시오. 앱이나 에이전트의 답변에서 인용을 위한 각 세그먼트에 비디오 링크를 추가합니다.

Canonical 참고: https://flashdata.dev/ko/docs/guides/timestamped-captions-recipe
검토: 2026-11-05 FlashData

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

## 시작하기 전에

youtube_captions 권한 및 사용 가능한 크레딧으로 키를 사용합니다. 제품 정보 Python 3.10+ 요청, 또는 Bash 으로 cURL 7.76+ 및 jq. Windows에서 Git Bash를 Bash 버전으로 사용하십시오.

- [API 키 받기](https://flashdata.dev/app/api-keys)
- [에이전트 체험 및 계정 연결](https://flashdata.dev/ko/docs/guides/agent-onboarding/reference.md)
- [크레딧 및 가격](https://flashdata.dev/ko/docs/guides/credits-and-billing/reference.md)

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

## 1. 비디오 및 캡션 트랙 선택

타임스탬프 캡션 폴더를 만들고 request.json를 저장하십시오. 그 폴더에 터미널을 엽니다. 비디오의 11-character ID를 사용하여 video_id를 교체하여 전체 URL가 아닙니다.

이 예제는 영어 자동 캡션을 요청합니다. auto=true로, en-orig를 첫째로 삼아, 그 후에 en. Explicit -orig 부호와 auto=false는 정확한 체재합니다. API는 자동 및 로더 보호된 캡션 사이에서 결코 전환하지 않습니다.

### timestamped-captions/request.json

```json
{
  "source": "youtube_captions",
  "video_id": "FUfGcZ092b0",
  "params": {
    "language": "en",
    "auto": true
  }
}
```

- [metadata의 후보자 언어 확인](https://flashdata.dev/ko/docs/guides/video-metadata-recipe/reference.md#fields)

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

## 2. Fetch 및 캡션 저장

하나의 버전을 선택하고 request.json 옆에 스크립트를 저장하십시오. 그것은 FLASHDATA_API_KEY를 읽거나 숨겨지은 프롬프트에서 당신의 열쇠를 요구한다. 에이전트는 자신의 비밀 저장소에서 환경 변수를로드해야합니다.

출력 폴더로 트랙-001로 실행합니다. 새 폴더는 하나의 쿼리를 보내고보고 된 사용법을 저장합니다. captions.json 만들기 전에, 스크립트는 반환된 비디오 ID, 언어, 캡션 기원 및 세그먼트 타이밍을 검증합니다.

### Python

#### Python 환경에서 설치

```bash
python -m pip install requests
```

#### timestamped-captions/captions.py

```python
import argparse
import getpass
import json
import math
import os
import re
from datetime import datetime, timezone
from pathlib import Path

import requests

parser = argparse.ArgumentParser()
parser.add_argument("folder", help="New output folder, or an existing saved caption request")
out = Path(parser.parse_args().folder)

if not out.exists():
    body = Path("request.json").read_bytes()
    request = json.loads(body)
    if (not isinstance(request, dict) or request.get("source") != "youtube_captions"
            or not isinstance(request.get("video_id"), str)
            or not re.fullmatch(r"[A-Za-z0-9_-]{11}", request["video_id"])):
        raise SystemExit("Use youtube_captions and an 11-character video_id")
    options = request.get("params")
    if (not isinstance(options, dict) or not isinstance(options.get("language"), str)
            or not re.fullmatch(r"[A-Za-z0-9-]{1,35}", options["language"])
            or type(options.get("auto")) is not bool):
        raise SystemExit("Set one language code and auto: true or false explicitly")
    key = os.environ.get("FLASHDATA_API_KEY") or getpass.getpass("FlashData API key: ")
    if not key.strip():
        raise SystemExit("An API key is required")
    out.mkdir()
    (out / "request.json").write_bytes(body)
    (out / "requested-at.txt").write_text(
        datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), encoding="utf-8"
    )
    try:
        response = requests.post(
            "https://data.flashdata.dev/v1/queries/realtime",
            headers={"X-API-Key": key, "Content-Type": "application/json",
                     "Accept": "application/json"},
            data=body, timeout=120, allow_redirects=False,
        )
    except requests.RequestException:
        raise SystemExit(f"Request interrupted. Keep {out} and check History before retrying.")
    (out / "result.json").write_bytes(response.content)
    (out / "response-headers.txt").write_text(
        "\n".join(f"{k}: {v}" for k, v in response.headers.items()), encoding="utf-8"
    )
    (out / "http-status.txt").write_text(str(response.status_code), encoding="utf-8")
else:
    print(f"Reading saved response from {out}; no API call.")

if not (out / "http-status.txt").exists():
    raise SystemExit("Incomplete attempt. Keep the folder and check History before retrying.")
status = (out / "http-status.txt").read_text().strip()
if status != "200":
    raise SystemExit(f"HTTP {status}: inspect {out}/result.json and response-headers.txt")
try:
    data = json.loads((out / "result.json").read_bytes())
except ValueError:
    raise SystemExit("Invalid JSON; inspect the saved result.json")
request = json.loads((out / "request.json").read_bytes())
if not isinstance(data, dict) or data.get("source") != "youtube_captions" or data.get("status") != "done":
    raise SystemExit("Caption request did not finish successfully; inspect result.json")
tracks = data.get("results")
if not isinstance(tracks, list) or len(tracks) != 1 or not isinstance(tracks[0], dict):
    raise SystemExit("Expected one caption track; inspect result.json")
track = tracks[0]
language = request["params"]["language"]
allowed_languages = [language]
if request["params"]["auto"] and not language.endswith("-orig"):
    allowed_languages.append(language + "-orig")
if (track.get("videoId") != request["video_id"]
        or track.get("languageCode") not in allowed_languages
        or track.get("requestedLanguageCode", track.get("languageCode")) != language
        or track.get("isAutoGenerated") is not request["params"]["auto"]):
    raise SystemExit("Returned video, language or caption origin does not match the request")
if not isinstance(track.get("segments"), list):
    raise SystemExit("Expected a segments array; inspect result.json")
segments = []
for cue in track["segments"]:
    if not isinstance(cue, dict):
        raise SystemExit("Expected caption segment objects")
    start, end, text = cue.get("start"), cue.get("end"), cue.get("text")
    if (type(start) not in (int, float) or not math.isfinite(start) or start < 0
            or type(end) not in (int, float) or not math.isfinite(end) or end < start
            or not isinstance(text, str)):
        raise SystemExit("Invalid caption timing or text; inspect result.json")
    segments.append({**cue, "url": f"https://www.youtube.com/watch?v={track['videoId']}&t={math.floor(start)}s"})
captions = {**track, "segments": segments}
record = {"request": request, "requested_at": (out / "requested-at.txt").read_text().strip(),
          "usage": data.get("usage"), "segment_count": len(segments), "result_file": "result.json"}
for filename, value in (("captions.json", captions), ("record.json", record)):
    (out / filename).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Saved {len(segments)} segments to {out}/captions.json")
if not any(cue["text"].strip() for cue in segments):
    print("No caption text to cite. Keep the empty track and report the gap.")
```

#### 타임스탬프 캡션에서 실행/

```bash
python captions.py track-001
```


### Bash

#### 당신의 도구를 확인

```bash
curl --version
jq --version
```

#### timestamped-captions/captions.sh

```bash
#!/usr/bin/env bash
set -euo pipefail
out="${1:?Usage: bash captions.sh OUTPUT_FOLDER}"

if [[ ! -e "$out" ]]; then
  jq -e '.source == "youtube_captions" and
    (.video_id | if type == "string" then length == 11 and test("^[A-Za-z0-9_-]{11}$") else false end) and
    (.params.language | if type == "string" then length > 0 and length <= 35 and
      (test("[^A-Za-z0-9-]") | not) else false end) and
    (.params.auto | type == "boolean")' request.json > /dev/null
  if [[ -z "${FLASHDATA_API_KEY:-}" ]]; then
    read -r -s -p "FlashData API key: " FLASHDATA_API_KEY
    printf '\n'
  fi
  : "${FLASHDATA_API_KEY:?An API key is required}"
  mkdir -- "$out"
  cp request.json "$out/request.json"
  date -u +'%Y-%m-%dT%H:%M:%SZ' > "$out/requested-at.txt"
  curl --fail-with-body --silent --show-error --max-time 120 \
    --request POST 'https://data.flashdata.dev/v1/queries/realtime' \
    --header "X-API-Key: $FLASHDATA_API_KEY" \
    --header 'Content-Type: application/json' --header 'Accept: application/json' \
    --data-binary "@$out/request.json" \
    --dump-header "$out/response-headers.txt" --output "$out/result.json" \
    --write-out '%{http_code}' > "$out/http-status.txt" || {
      printf 'Request failed. Keep %s and inspect its saved files before retrying.\n' "$out" >&2
      exit 1
    }
else
  printf 'Reading saved response from %s; no API call.\n' "$out"
fi

if [[ ! -f "$out/http-status.txt" ]] || [[ "$(cat "$out/http-status.txt")" != 200 ]]; then
  printf 'Incomplete or failed attempt. Inspect the saved files and History before retrying.\n' >&2
  exit 1
fi
captions=$(jq -e --slurpfile request "$out/request.json" '
  if .source != "youtube_captions" or .status != "done"
  then error("Expected a successful youtube_captions response") else . end
  | .results
  | if type != "array" then error("Expected a results array")
    elif length != 1 then error("Expected exactly one track") else .[0] end
  | $request[0].params.language as $language
  | if type != "object" then error("Expected a caption object")
    elif .videoId != $request[0].video_id or (.requestedLanguageCode // .languageCode) != $language
      or (.languageCode != $language and ($request[0].params.auto != true
        or ($language | endswith("-orig")) or .languageCode != ($language + "-orig")))
      or .isAutoGenerated != $request[0].params.auto
    then error("Returned video, language or caption origin does not match the request") else . end
  | if (.segments | type) != "array" then error("Expected a segments array") else . end
  | .videoId as $id
  | .segments |= map(
      if type != "object" then error("Expected caption segment objects") else . end
      | if (.start | type) != "number" or (.end | type) != "number" or (.text | type) != "string"
        then error("Invalid caption timing or text")
        elif (.start | isfinite | not) or (.end | isfinite | not) or .start < 0 or .end < .start
        then error("Invalid caption timing")
        else . + {url: ("https://www.youtube.com/watch?v=" + $id + "&t=" + (.start | floor | tostring) + "s")} end
    )' "$out/result.json")
printf '%s\n' "$captions" > "$out/captions.json"
jq --slurpfile request "$out/request.json" --slurpfile captions "$out/captions.json" \
  --arg requested_at "$(tr -d '\r\n' < "$out/requested-at.txt")" \
  '{request: $request[0], requested_at: $requested_at, usage,
    segment_count: ($captions[0].segments | length), result_file: "result.json"}' \
  "$out/result.json" > "$out/record.json"
printf 'Saved %s segments to %s/captions.json\n' "$(jq '.segments | length' "$out/captions.json")" "$out"
if ! jq -e 'any(.segments[]; .text | test("\\S"))' "$out/captions.json" > /dev/null; then
  printf 'No caption text to cite. Keep the empty track and report the gap.\n'
fi
```

#### 타임스탬프 캡션에서 실행/

```bash
bash captions.sh track-001
```



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

## 3. 타임스탬프 텍스트 읽기

track-001/captions.json.에 저장된 N 세그먼트를 성공적으로 인쇄하십시오 이 파일은 반환된 트랙을 보존하고 각 세그먼트에 URL를 추가합니다. record.json는 정확한 제출된 요청, requested_at, 사용 및 segment_count; result.json는 원래 API 응답을 유지합니다.

### Python

#### 로컬로 읽기 · API 통화 없음

```bash
python -m json.tool track-001/captions.json
python -m json.tool track-001/record.json
```


### Bash

#### 로컬로 읽기 · API 통화 없음

```bash
cat track-001/captions.json
cat track-001/record.json
```



<a id="expected"></a>

### 예 출력

설명 captions.json. 텍스트와 타이밍이 다릅니다. languageName는 null일 수 있습니다. 스크립트는 그 방법을 유지합니다.

#### timestamped-captions/track-001/captions.json

```json
{
  "videoId": "FUfGcZ092b0",
  "languageCode": "en",
  "languageName": null,
  "isAutoGenerated": true,
  "segments": [
    {
      "start": 12.5,
      "end": 16.2,
      "text": "This is an illustrative caption segment.",
      "url": "https://www.youtube.com/watch?v=FUfGcZ092b0&t=12s"
    }
  ]
}
```


<a id="cite"></a>

## 비디오 통행을 Cite

소스 링크와 함께 첫 번째 세 세그먼트를 인쇄합니다. 시작과 끝은 원래 정밀도로 초에 머물. URL의 시작 시간이 떨어졌습니다. 12.5 초는 &t=12s가 됩니다. 세그먼트 순서와 overlapping 타이밍은 보존됩니다.

### Python

captions.py 외에 cite.py를 저장하고, 같은 폴더에서 실행합니다.

#### timestamped-captions/cite.py

```python
import json
from pathlib import Path

captions = json.loads(Path("track-001/captions.json").read_text(encoding="utf-8"))
for cue in captions["segments"][:3]:
    print(f"[{cue['start']}–{cue['end']}s] {cue['text']}")
    print(cue["url"])
    print()
```

#### 저장된 captions에서 인쇄 인용

```bash
python cite.py
```


### Bash

#### 저장된 captions에서 인쇄 인용

```bash
jq -r '.segments[:3][] |
  "[\(.start)–\(.end)s] \(.text)\n\(.url)\n"' track-001/captions.json
```


- [citations와 요약 작성](https://flashdata.dev/ko/docs/guides/youtube-summary/reference.md)

<a id="evidence"></a>

### 캡션 컨텍스트 유지

인용에 대한 증거로 세그먼트 텍스트를 사용; fullText는 읽기에 유용하지만 통행을 찾을 수 없습니다. 자동 캡션을 위해 특히 인용하기 전에 주변 세그먼트를 확인하십시오. languageCode 및 isAutoGenerated를 유지하므로 앱 또는 에이전트는 소스 트랙을 식별 할 수 있습니다.


<a id="reuse"></a>

## 저장된 트랙을 재사용

저장된 응답에서 captions.json를 재구축하기 위한 동일한 명령을 실행하고, 열쇠 또는 새로운 쿼리 없이. 최고 수준의 request.json 편집은 트랙-001로 저장된 요청을 변경하지 않습니다.

### Python

#### 현지에서 사용

```bash
python captions.py track-001
```


### Bash

#### 현지에서 사용

```bash
bash captions.sh track-001
```



<a id="track"></a>

### 다른 트랙을 선택

업로드 프로그램 제공 영어 자막을 요청하려면, 이 버전과 request.json를 대체하고 트랙-002를 사용하십시오. 변경 언어는 en-orig 또는 zh-Hans와 같은 검색 할 코드에만. Metadata의 transcriptLanguages 목록 후보 코드는 자동 또는 업로드 된 트랙이 있는지 여부.

스크립트는 하나의 언어 문자열을 기대합니다. 언어 배열에는 트랙과 언어 오류가 다른 응답 형태가 있습니다. API 참조를 사용하여 작업 흐름을 지원합니다.

#### timestamped-captions/request.json

```json
{
  "source": "youtube_captions",
  "video_id": "FUfGcZ092b0",
  "params": {
    "language": "en",
    "auto": false
  }
}
```

#### Python

##### 새로운 트랙 · 다른 API 요청

```bash
python captions.py track-002
```


#### Bash

##### 새로운 트랙 · 다른 API 요청

```bash
bash captions.sh track-002
```


- [Caption 모수와 응답 모양](https://flashdata.dev/ko/docs/sources/youtube_captions/reference.md)

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

## captions가 누락되거나 무해한 경우

| 어떤 일이 있었는지 | 해결 방법 |
| --- | --- |
| 선택한 트랙은 사용할 수 없습니다 | 비디오, 언어 및 자동 선택 확인. 명시적으로 유효한 트랙을 선택하십시오. 동일한 요청을 반복하면 캡션을 만들 수 없습니다. |
| segments: [] | 기존 트랙은 텍스트가 포함될 수 있습니다. 스크립트는 빈 트랙을 저장하고 간격을보고. 성적표 또는 요약에 표시하지 마십시오. |
| 잘못된 비디오, 언어 또는 caption 기원 | captions.json는 작성되지 않습니다. 모든 텍스트를 사용하기 전에 result.json와 저장된 요청을 비교하십시오. |
| 잘못된 타이밍 또는 누락된 세그먼트 | result.json를 검사하십시오. 스크립트는 timetamps 또는 침묵적으로 나쁜 세그먼트를 할당 대신 중지합니다. |
| 401 / 403 / 402 | 키, youtube_captions 권한 및 균형 확인, 각각, 새로운 시도 전에. |
| 429 | response-headers.txt에서 Retry-After를 읽고 기다립니다. 스크립트는 자동으로 재시동하지 않습니다. |
| Timeout, 5xx, 잘못된 JSON 또는 불완전 폴더 | 다시 제출하기 전에 History를 시도하고 확인하십시오. 폴더를 재사용하면 다른 쿼리를 보낼 수 없습니다. |

### Python

captions.py 옆에 inspect_captions.py를 저장하고, 그 후에 그것을 달립니다.

#### timestamped-captions/inspect_captions.py

```python
from pathlib import Path

for name in ("http-status.txt", "response-headers.txt", "result.json"):
    path = Path("track-001") / name
    print(f"--- {name} ---")
    print(path.read_text(encoding="utf-8", errors="replace") if path.exists() else "Not saved")
```

#### 로컬로 검사

```bash
python inspect_captions.py
```


### Bash

#### 로컬로 검사

```bash
for name in http-status.txt response-headers.txt result.json; do
  printf '\n--- %s ---\n' "$name"
  if [[ -f "track-001/$name" ]]; then cat "track-001/$name"; else printf 'Not saved\n'; fi
done
```


- [회사연혁](https://flashdata.dev/app/jobs)
- [오류와 상태 코드](https://flashdata.dev/ko/docs/errors/reference.md)
