youtube-transcript-plus

repository·main·Indexed 41 days ago

https://github.com/ericmmartin/youtube-transcript-plus

A Node.js library for fetching YouTube video transcripts using an unofficial API. Version 2.0.1 supports custom caching strategies (InMemoryCache, FsCache), proxy support via custom fetch functions, and conversion of transcripts to SRT, WebVTT, or plain text formats. It includes utilities to list available caption languages and provides detailed error handling for unavailable videos or disabled transcripts.

Tokens
7.7K
Snippets
26
Records
29
Agent score
38%

What's inside youtube-transcript-plus

  1. Implement and use custom caching strategies

    main

    The library supports caching to avoid redundant requests. You can use built-in strategies or implement the CacheStrategy interface.

    Built-in: In-Memory Cache

    Use InMemoryCache for transient, memory-based caching.

    Built-in: File System Cache

    Use FsCache to persist cache to a directory.

    Custom Cache

    Implement the get and set methods of the CacheStrategy interface.

    import { fetchTranscript, InMemoryCache, FsCache, CacheStrategy } from 'youtube-transcript-plus';
    
    // In-Memory
    fetchTranscript('videoId', { cache: new InMemoryCache(1800000) });
    
    // File System
    fetchTranscript('videoId', { cache: new FsCache('./my-cache-dir', 86400000) });
    
    // Custom
    class CustomCache implements CacheStrategy {
      async get(key: string): Promise<string | null> { /* ... */ }
      async set(key: string, value: string, ttl?: number): Promise<void> { /* ... */ }
    }
    fetchTranscript('videoId', { cache: new CustomCache() });
  2. Analyze TranscriptResult and TranscriptSegment

    main

    When videoDetails is set to true in the configuration, the library returns a TranscriptResult. This object combines video metadata with the actual transcript data.

    TranscriptResult:

    • videoDetails: A VideoDetails object containing metadata like title, author, description, and thumbnails.
    • segments: An array of TranscriptSegment objects.

    TranscriptSegment: Each segment represents a slice of the transcript:

    • text: The actual spoken text.
    • duration: Duration of the segment in seconds.
    • offset: Start time of the segment in seconds.
    • lang: The language code of the segment.
    export interface TranscriptResult {
      videoDetails: VideoDetails;
      segments: TranscriptSegment[];
    }
    
    export interface TranscriptSegment {
      text: string;
      duration: number;
      offset: number;
      lang: string;
    }
  3. Configure fetchTranscript options

    main

    The fetchTranscript function accepts an optional TranscriptConfig object to customize the request behavior:

    PropertyTypeDescription
    langstringBCP 47 language code (e.g., 'en', 'fr')
    userAgentstringCustom User-Agent string
    cacheCacheStrategyCustom caching strategy implementation
    cacheTTLnumberTime-to-live for cache entries in milliseconds
    disableHttpsbooleanIf true, uses HTTP instead of HTTPS
    videoFetchFunctionCustom fetch function for the video page (GET)
    playerFetchFunctionCustom fetch function for the YouTube Innertube API (POST)
    transcriptFetchFunctionCustom fetch function for the transcript data (GET)
    retriesnumberMax retry attempts for 429/5xx errors (default: 0)
    retryDelaynumberBase delay for exponential backoff in ms (default: 1000)
    signalAbortSignalUsed to cancel in-flight requests
    videoDetailsbooleanIf true, returns TranscriptResult instead of TranscriptSegment[]
  4. List available caption languages

    main

    Use listLanguages to discover which caption tracks are available for a video without downloading the full transcript.

    import { listLanguages } from 'youtube-transcript-plus';
    
    const languages = await listLanguages('videoId_or_URL');
    // Returns array of: { languageCode: string, languageName: string, isAutoGenerated: boolean }
  5. List available caption languages with listLanguages()

    main

    Use listLanguages(videoId, config) to check which caption tracks are available for a video without downloading the full transcript data. This is useful for determining if a specific language is supported before attempting to fetch it.

    Returns a Promise<CaptionTrackInfo[]> where each object contains:

    • languageCode: BCP 47 language code.
    • languageName: Human-readable name (e.g., 'English').
    • isAutoGenerated: Boolean indicating if the track is auto-generated.
    const languages = await listLanguages('VIDEO_ID');
    console.log(languages);
  6. Fetch YouTube transcripts with fetchTranscript()

    main

    Use fetchTranscript(videoId, config) to retrieve the transcript for a specific YouTube video.

    By default, it returns an array of TranscriptSegment objects. If you set videoDetails: true in the configuration, it returns a TranscriptResult object containing both the video metadata and the transcript segments.

    TranscriptSegment properties:

    • text: The text content.
    • duration: Duration in seconds.
    • offset: Start time in seconds.
    • lang: Language code.

    TranscriptResult properties (when videoDetails: true):

    • videoDetails: Object containing title, author, channelId, lengthSeconds, viewCount, description, keywords, thumbnails, and isLiveContent.
    • segments: Array of TranscriptSegment objects.
    // Basic usage returning segments
    const segments = await fetchTranscript('VIDEO_ID');
    
    // Usage with video metadata
    const result = await fetchTranscript('VIDEO_ID', { videoDetails: true });
    console.log(result.videoDetails.title);
  7. Convert transcripts to SRT, VTT, or Plain Text

    main

    Once you have retrieved TranscriptSegment[], you can convert them into various formats using the following utility functions:

    • toSRT(segments): Converts segments to SubRip (SRT) format with sequence numbers and HH:MM:SS,mmm timestamps.
    • toVTT(segments): Converts segments to WebVTT format with a WEBVTT header and HH:MM:SS.mmm timestamps.
    • toPlainText(segments, separator?): Converts segments to plain text. The separator defaults to \n.
    const segments = await fetchTranscript('VIDEO_ID');
    
    const srt = toSRT(segments);
    const vtt = toVTT(segments);
    const text = toPlainText(segments, ' ');
  8. Fetch a YouTube transcript with fetchTranscript()

    main

    Use fetchTranscript to retrieve transcript segments for a given video ID or URL. By default, it returns an array of transcript segments.

    import { fetchTranscript } from 'youtube-transcript-plus';
    
    // Fetch transcript using default settings
    fetchTranscript('videoId_or_URL').then(console.log).catch(console.error);
  9. Convert transcripts to different formats

    main

    Once you have a transcript, use the utility functions to convert the segments into common subtitle formats or plain text.

    • toSRT(transcript): Converts to SubRip format.
    • toVTT(transcript): Converts to WebVTT format.
    • toPlainText(transcript, [separator]): Converts to plain text. Defaults to one line per segment. You can provide a custom separator (e.g., ' ').
    import { fetchTranscript, toSRT, toVTT, toPlainText } from 'youtube-transcript-plus';
    
    const transcript = await fetchTranscript('videoId_or_URL');
    
    const srt = toSRT(transcript);
    const vtt = toVTT(transcript);
    const text = toPlainText(transcript);
    const paragraph = toPlainText(transcript, ' ');
  10. Inject custom fetch functions

    main

    You can override the internal HTTP request logic by providing custom implementations for the three types of requests the library makes. This is useful for using proxies or custom headers.

    1. videoFetch: Fetches the YouTube video page (GET).
    2. playerFetch: Calls YouTube's Innertube API to get caption tracks (POST).
    3. transcriptFetch: Downloads the actual transcript data (GET).
    fetchTranscript('videoId_or_URL', {
      videoFetch: async ({ url, lang, userAgent }) => {
        return fetch(`https://my-proxy-server.com/?url=${encodeURIComponent(url)}`, {
          headers: {
            ...(lang && { 'Accept-Language': lang }),
            'User-Agent': userAgent,
          },
        });
      },
      playerFetch: async ({ url, method, body, headers, lang, userAgent }) => {
        return fetch(`https://my-proxy-server.com/?url=${encodeURIComponent(url)}`, {
          method,
          headers: {
            ...(lang && { 'Accept-Language': lang }),
            'User-Agent': userAgent,
            ...headers,
          },
          body,
        });
      },
      transcriptFetch: async ({ url, lang, userAgent }) => {
        return fetch(`https://my-proxy-server.com/?url=${encodeURIComponent(url)}`, {
          headers: {
            ...(lang && { 'Accept-Language': lang }),
            'User-Agent': userAgent,
          },
        });
      },
    })
      .then(console.log)
      .catch(console.error);
  11. Configure transcript fetching with TranscriptConfig

    main

    The TranscriptConfig object allows you to customize the behavior of the transcript fetching process. You can control language preferences, user agents, caching, and even provide custom fetch implementations for different parts of the YouTube request lifecycle.

    Key configuration options:

    • lang: BCP 47 language code (e.g., 'en').
    • userAgent: Custom User-Agent string.
    • cache: An object implementing the CacheStrategy interface.
    • cacheTTL: Time-to-live for cache entries in milliseconds (defaults to 1 hour).
    • videoDetails: Set to true to return a TranscriptResult containing both video metadata and segments.
    • retries: Maximum retry attempts for transient failures (429, 5xx). Defaults to 0.
    • retryDelay: Base delay in milliseconds for exponential backoff. Defaults to 1000.
    • signal: An AbortSignal to cancel in-flight requests.
    • disableHttps: Use HTTP instead of HTTPS (not recommended for production).

    Custom Fetch Functions: You can override the default fetching logic by providing custom functions that accept FetchParams and return a Promise<Response>:

    • videoFetch: For the YouTube watch page (GET).
    • transcriptFetch: For the transcript XML data (GET).
    • playerFetch: For the YouTube Innertube player API (POST).
    export interface TranscriptConfig {
      lang?: string;
      userAgent?: string;
      cache?: CacheStrategy;
      cacheTTL?: number;
      disableHttps?: boolean;
      videoFetch?: (params: FetchParams) => Promise<Response>;
      transcriptFetch?: (params: FetchParams) => Promise<Response>;
      playerFetch?: (params: FetchParams) => Promise<Response>;
      retries?: number;
      retryDelay?: number;
      signal?: AbortSignal;
      videoDetails?: boolean;
    }