# Lấy phụ đề thời gian

Lưu một tập tin đã có YouTube theo dõi bài viết, thời gian và ngôn ngữ. Thêm một liên kết video đến mỗi đoạn để trích dẫn trong ứng dụng hoặc tác nhân của bạn.

Tài liệu tham khảo chính điển: https://flashdata.dev/vi/docs/guides/timestamped-captions-recipe
Xem lại: 2026-11-05 by FlashData

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

## Trước khi bắt đầu

Dùng phím youtube_captions Cho phép và tín dụng sẵn có. Chọn Python 3.10+ với yêu cầu, hoặc Bash có cURL 7.76+ và jq. Vào Windowssử dụng Git Bash cho Bash phiên bản.

- [Lấy khóa API](https://flashdata.dev/app/api-keys)
- [Dùng thử tác nhân và liên kết tài khoản](https://flashdata.dev/vi/docs/guides/agent-onboarding/reference.md)
- [Tín dụng và giá cả](https://flashdata.dev/vi/docs/guides/credits-and-billing/reference.md)

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

## 1. Chọn đoạn phim và phần chú thích

Tạo một thư mục phụ tùng thời gian và lưu request.json ở đó. Mở một thiết bị cuối trong thư mục đó. Thay thế video_id với video 11- Hồ sơ. IDChưa đầy đâu. URL.

Ví dụ này yêu cầu tiếng Anh tự động phụ đề. Với tự động =true, en cố en-oig đầu tiên, sau đó en. Explicit -ig mã và tự động =false Giữ nguyên vị trí. Hạt API Không bao giờ chuyển giao giữa tự động và phụ đề tải lên.

### timestamped-captions/request.json

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

- [Kiểm tra các ngôn ngữ ứng cử viên trong siêu dữ liệu](https://flashdata.dev/vi/docs/guides/video-metadata-recipe/reference.md#fields)

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

## 2. Lấy và lưu chú thích

Chọn một phiên bản và lưu văn lệnh bên cạnh request.json. Nó đọc FLASHDATA_API_KEY hoặc yêu cầu chìa khóa của bạn tại một dấu nhắc ẩn. Các tác nhân nên tải biến môi trường đó từ cửa hàng bí mật của họ.

Chạy với đường ray...001 là thư mục xuất. Một thư mục mới gửi một yêu cầu và lưu cách sử dụng đã báo cáo. Trước khi tạo captions.json, kịch bản xác minh video đã quay lại IDNgôn ngữ, tiêu đề và thời gian phân đoạn.

### Python

#### Cài đặt trong môi trường Python của bạn

```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.")
```

#### Chạy từ tập tin đóng dấu thời gian/

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


### Bash

#### Kiểm tra dụng cụ của bạn

```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
```

#### Chạy từ tập tin đóng dấu thời gian/

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



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

## 3. Đọc văn bản nhãn thời gian

Thành công in các đoạn N tới track-001/captions.json. Tập tin đó bảo tồn các đường ray trở về và thêm một URL cho mỗi đoạn. record.json chứa chính xác yêu cầu nộp đơn, requested_atCách sử dụng và segment_count; result.json giữ lại bản gốc API Trả lời đi.

### Python

#### Đọc · no tại địa phương API cuộc gọi

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


### Bash

#### Đọc · no tại địa phương API cuộc gọi

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



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

### Đầu ra Ví dụ

Được viết tắt, minh họa captions.json. Tin nhắn và thời gian của bạn sẽ khác nhau. languageName Có thể null; kịch bản giữ cho nó như vậy.

#### 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>

## Lấy một đoạn phim

In ba đoạn đầu với liên kết gốc của chúng. Bắt đầu và kết thúc trong giây với độ chính xác ban đầu. Chỉ có URLThời gian bắt đầu của được làm tròn xuống: 12.5 giây trở thành & t=12s. Thứ tự co giật và canh thời gian chồng chéo được bảo quản.

### Python

Lưu cite.py bên cạnh captions.pySau đó, chạy nó từ cùng một tập tin.

#### 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()
```

#### In đoạn trích dẫn từ đầu đề đã lưu

```bash
python cite.py
```


### Bash

#### In đoạn trích dẫn từ đầu đề đã lưu

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


- [Xây dựng một bản tóm tắt bằng lời trích dẫn](https://flashdata.dev/vi/docs/guides/youtube-summary/reference.md)

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

### Giữ đoạn đầu

Dùng đoạn văn để làm bằng chứng cho lời trích dẫn; fullText rất hữu ích cho việc đọc nhưng không tìm được đoạn nào. Kiểm tra các đoạn xung quanh trước khi trích dẫn, đặc biệt là phần phụ đề tự động. Giữ lại languageCode và isAutoGenerated Vì vậy, ứng dụng hoặc tác nhân của bạn có thể xác định theo dõi nguồn.


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

## Dùng lại dấu vết đã lưu

Chạy cùng một lệnh để xây dựng lại captions.json từ câu trả lời đã lưu, mà không cần chìa khóa hoặc truy vấn mới. Sửa chữa cấp cao request.json không thay đổi yêu cầu được lưu trữ theo dõi-001.

### Python

#### Dùng lại cục bộ

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


### Bash

#### Dùng lại cục bộ

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



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

### Chọn một đường

Để yêu cầu tải lên tiêu đề tiếng Anh, thay thế request.json Với phiên bản này và theo dõi...002. Thay đổi ngôn ngữ chỉ thành mật mã mà bạn định lấy, như en-o-rig hoặc zh-Hoans. Siêu dữ liệu transcriptLanguages Danh sách các mã ứng cử viên, không phải cho dù mỗi cái có một dấu vết tự động hay được tải lên.

Văn lệnh mong đợi một chuỗi ngôn ngữ. Các dãy ngôn ngữ có một hình phản ứng khác nhau với dấu vết và lỗi per-language; sử dụng các API Tham khảo cho dòng chảy công việc đó.

#### timestamped-captions/request.json

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

#### Python

##### Đường ray mới # khác API yêu cầu

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


#### Bash

##### Đường ray mới # khác API yêu cầu

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


- [Tham số điểm ảnh và hình phản ứng](https://flashdata.dev/vi/docs/sources/youtube_captions/reference.md)

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

## Nếu thiếu phụ đề hoặc không thể sử dụng

| Chuyện gì đã xảy ra | Cách xử lý |
| --- | --- |
| Đường dẫn đã chọn không sẵn sàng | Kiểm tra đoạn video, ngôn ngữ và sự lựa chọn tự động. Hãy chọn một đường dẫn sẵn sàng; lặp đi lặp lại cùng yêu cầu sẽ không tạo chú thích. |
| segments: [] | Một dấu vết tồn tại không thể chứa văn bản. Văn lệnh lưu đường dẫn trống và báo cáo khoảng trống. Đừng biến nó thành bản sao hoặc tóm tắt. |
| Nguồn phim, ngôn ngữ hoặc tiêu đề sai | Không có captions.json nào được viết ra. So sánh yêu cầu lưu với result.json trước khi dùng bất kỳ văn bản nào. |
| Thời gian hoặc đoạn còn thiếu không hợp lệ | Kiểm tra result.json. Văn lệnh dừng lại thay vì chỉ định các nhãn hiệu thời gian hoặc âm thầm thả một đoạn xấu. |
| 401 / 403 / 402 | Kiểm tra chìa khóa đi. youtube_captions cho phép và số dư trước một nỗ lực mới. |
| 429 | Đọc Retry-After in response-headers.txt và chờ đợi. Văn lệnh không tự động thử lại. |
| Thời hạn, 5xx, không hợp lệ JSON hoặc thư mục không đầy đủ | Cứ tiếp tục cố gắng và kiểm tra History trước khi nộp lại. Dùng lại thư mục của nó không bao giờ gửi thêm một yêu cầu nào nữa. |

### Python

Lưu inspect_captions.py bên cạnh captions.pyVậy thì chạy đi.

#### 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")
```

#### Kiểm tra cục bộ

```bash
python inspect_captions.py
```


### Bash

#### Kiểm tra cục bộ

```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
```


- [Yêu cầu lịch sử](https://flashdata.dev/app/jobs)
- [Lỗi và mã trạng thái](https://flashdata.dev/vi/docs/errors/reference.md)
