yt-transcript-rs 0.1.1

A Rust library for fetching and working with YouTube video transcripts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use reqwest::Client;
use std::collections::HashMap;
use std::fmt;

use crate::errors::{CouldNotRetrieveTranscript, CouldNotRetrieveTranscriptReason};
use crate::fetched_transcript::FetchedTranscript;
use crate::models::TranslationLanguage;
use crate::transcript_parser::TranscriptParser;

/// # Transcript
///
/// Represents a YouTube transcript that can be fetched or translated.
///
/// This struct contains the metadata and access URLs for a transcript but not
/// the actual transcript text content. It serves as a handle to retrieve the
/// full transcript text when needed.
///
/// A `Transcript` object can represent:
/// - A native transcript in its original language
/// - A translatable transcript that can be converted to other languages
/// - A manually created transcript (more accurate, created by humans)
/// - An automatically generated transcript (created by YouTube's speech recognition)
///
/// ## Usage Example
///
/// ```rust,no_run
/// # use yt_transcript_rs::YouTubeTranscriptApi;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let api = YouTubeTranscriptApi::new(None, None, None)?;
/// let transcript_list = api.list_transcripts("dQw4w9WgXcQ").await?;
///
/// // Find an English transcript
/// let transcript = transcript_list.find_transcript(&["en"])?;
///
/// // Check if it can be translated
/// if transcript.is_translatable() {
///     // Translate to Spanish
///     let spanish = transcript.translate("es")?;
///     
///     // Fetch the translated content
///     let fetched = spanish.fetch(false).await?;
///     println!("Spanish transcript: {}", fetched.text());
/// }
///
/// // Or fetch the original transcript
/// let fetched = transcript.fetch(false).await?;
/// println!("Original transcript: {}", fetched.text());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Transcript {
    /// HTTP client for making requests to YouTube
    pub client: Client,

    /// The YouTube video ID this transcript belongs to
    pub video_id: String,

    /// URL to fetch the transcript content from YouTube
    pub url: String,

    /// Full human-readable language name (e.g., "English")
    pub language: String,

    /// Language code (e.g., "en", "en-US", "es")
    pub language_code: String,

    /// Whether this transcript was automatically generated by YouTube
    pub is_generated: bool,

    /// List of languages this transcript can be translated to
    pub translation_languages: Vec<TranslationLanguage>,

    /// Mapping of language codes to language names for available translations
    pub translation_languages_map: HashMap<String, String>,
}

impl Transcript {
    /// Creates a new transcript instance.
    ///
    /// This constructor creates a transcript object that can be used to fetch
    /// the actual transcript content or to generate translations.
    ///
    /// # Parameters
    ///
    /// * `client` - HTTP client for making requests to YouTube
    /// * `video_id` - YouTube video ID
    /// * `url` - URL to fetch the transcript content
    /// * `language` - Human-readable language name (e.g., "English")
    /// * `language_code` - Language code (e.g., "en", "en-US")
    /// * `is_generated` - Whether this transcript was automatically generated
    /// * `translation_languages` - List of languages this transcript can be translated to
    ///
    /// # Returns
    ///
    /// A new `Transcript` instance
    ///
    /// # Example (internal usage)
    ///
    /// ```rust,no_run
    /// # use reqwest::Client;
    /// # use yt_transcript_rs::transcript::Transcript;
    /// # use yt_transcript_rs::models::TranslationLanguage;
    /// # fn example() {
    /// let client = Client::new();
    ///
    /// // Create a transcript for English
    /// let transcript = Transcript::new(
    ///     client,
    ///     "dQw4w9WgXcQ".to_string(),
    ///     "https://www.youtube.com/api/timedtext?...".to_string(),
    ///     "English".to_string(),
    ///     "en".to_string(),
    ///     false, // Not automatically generated
    ///     vec![
    ///         TranslationLanguage {
    ///             language: "Spanish".to_string(),
    ///             language_code: "es".to_string()
    ///         }
    ///     ]
    /// );
    /// # }
    /// ```
    pub fn new(
        client: Client,
        video_id: String,
        url: String,
        language: String,
        language_code: String,
        is_generated: bool,
        translation_languages: Vec<TranslationLanguage>,
    ) -> Self {
        let translation_languages_map = translation_languages
            .iter()
            .map(|lang| (lang.language_code.clone(), lang.language.clone()))
            .collect();

        Self {
            client,
            video_id,
            url,
            language,
            language_code,
            is_generated,
            translation_languages,
            translation_languages_map,
        }
    }

    /// Fetches the actual transcript content from YouTube.
    ///
    /// This method retrieves the transcript text and timing information from YouTube
    /// and returns it as a structured `FetchedTranscript` object.
    ///
    /// # Parameters
    ///
    /// * `preserve_formatting` - Whether to preserve HTML formatting in the transcript
    ///   (e.g., bold, italic, etc.)
    ///
    /// # Returns
    ///
    /// * `Result<FetchedTranscript, CouldNotRetrieveTranscript>` - The fetched transcript or an error
    ///
    /// # Errors
    ///
    /// This method will return an error if:
    /// - The network request to YouTube fails
    /// - YouTube returns a non-OK status code
    /// - The transcript data cannot be parsed
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use yt_transcript_rs::YouTubeTranscriptApi;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let api = YouTubeTranscriptApi::new(None, None, None)?;
    /// let transcript_list = api.list_transcripts("dQw4w9WgXcQ").await?;
    /// let transcript = transcript_list.find_transcript(&["en"])?;
    ///
    /// // Fetch without preserving formatting
    /// let plain_transcript = transcript.fetch(false).await?;
    ///
    /// // Fetch and preserve HTML formatting like <b>bold</b> text
    /// let formatted_transcript = transcript.fetch(true).await?;
    ///
    /// // Access the full text
    /// println!("Transcript: {}", plain_transcript.text());
    ///
    /// // Or iterate through individual segments
    /// for segment in plain_transcript.parts() {
    ///     println!("[{:.1}s]: {}", segment.start, segment.text);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn fetch(
        &self,
        preserve_formatting: bool,
    ) -> Result<FetchedTranscript, CouldNotRetrieveTranscript> {
        let response =
            self.client
                .get(&self.url)
                .send()
                .await
                .map_err(|e| CouldNotRetrieveTranscript {
                    video_id: self.video_id.clone(),
                    reason: Some(CouldNotRetrieveTranscriptReason::YouTubeRequestFailed(
                        e.to_string(),
                    )),
                })?;

        if response.status() != reqwest::StatusCode::OK {
            return Err(CouldNotRetrieveTranscript {
                video_id: self.video_id.clone(),
                reason: Some(CouldNotRetrieveTranscriptReason::YouTubeRequestFailed(
                    format!("YouTube returned status code: {}", response.status()),
                )),
            });
        }

        let text = response
            .text()
            .await
            .map_err(|e| CouldNotRetrieveTranscript {
                video_id: self.video_id.clone(),
                reason: Some(CouldNotRetrieveTranscriptReason::YouTubeRequestFailed(
                    e.to_string(),
                )),
            })?;

        let snippets = TranscriptParser::new(preserve_formatting)
            .parse(&text.clone())
            .map_err(|_| CouldNotRetrieveTranscript {
                video_id: self.video_id.clone(),
                reason: Some(CouldNotRetrieveTranscriptReason::YouTubeDataUnparsable),
            })?;

        Ok(FetchedTranscript {
            snippets,
            video_id: self.video_id.clone(),
            language: self.language.clone(),
            language_code: self.language_code.clone(),
            is_generated: self.is_generated,
        })
    }

    /// Checks if this transcript can be translated to other languages.
    ///
    /// This method determines whether YouTube offers translation capabilities
    /// for this transcript. Not all transcripts are translatable.
    ///
    /// # Returns
    ///
    /// * `bool` - `true` if this transcript can be translated, `false` otherwise
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use yt_transcript_rs::YouTubeTranscriptApi;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let api = YouTubeTranscriptApi::new(None, None, None)?;
    /// let transcript_list = api.list_transcripts("dQw4w9WgXcQ").await?;
    /// let transcript = transcript_list.find_transcript(&["en"])?;
    ///
    /// if transcript.is_translatable() {
    ///     println!("This transcript can be translated to other languages");
    ///     
    ///     // Available translation languages
    ///     for lang in &transcript.translation_languages {
    ///         println!("- {} ({})", lang.language, lang.language_code);
    ///     }
    /// } else {
    ///     println!("This transcript cannot be translated");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_translatable(&self) -> bool {
        !self.translation_languages.is_empty()
    }

    /// Creates a translated version of this transcript in the specified language.
    ///
    /// This method creates a new `Transcript` instance representing the same content
    /// but translated to the requested language. Note that this doesn't actually perform
    /// the translation yet - the translation happens when you call `fetch()` on the
    /// returned transcript.
    ///
    /// # Parameters
    ///
    /// * `language_code` - The language code to translate to (e.g., "es" for Spanish)
    ///
    /// # Returns
    ///
    /// * `Result<Self, CouldNotRetrieveTranscript>` - A new transcript object representing
    ///   the translation, or an error
    ///
    /// # Errors
    ///
    /// This method will return an error if:
    /// - The transcript is not translatable
    /// - The requested language is not available for translation
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use yt_transcript_rs::YouTubeTranscriptApi;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let api = YouTubeTranscriptApi::new(None, None, None)?;
    /// let transcript_list = api.list_transcripts("dQw4w9WgXcQ").await?;
    /// let transcript = transcript_list.find_transcript(&["en"])?;
    ///
    /// // Create Spanish translation
    /// if transcript.is_translatable() {
    ///     let spanish = transcript.translate("es")?;
    ///     
    ///     // Now fetch the Spanish translation
    ///     let spanish_content = spanish.fetch(false).await?;
    ///     println!("Spanish: {}", spanish_content.text());
    ///     
    ///     // Create Japanese translation
    ///     let japanese = transcript.translate("ja")?;
    ///     let japanese_content = japanese.fetch(false).await?;
    ///     println!("Japanese: {}", japanese_content.text());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn translate(&self, language_code: &str) -> Result<Self, CouldNotRetrieveTranscript> {
        if !self.is_translatable() {
            return Err(CouldNotRetrieveTranscript {
                video_id: self.video_id.clone(),
                reason: Some(CouldNotRetrieveTranscriptReason::NotTranslatable),
            });
        }

        if !self.translation_languages_map.contains_key(language_code) {
            return Err(CouldNotRetrieveTranscript {
                video_id: self.video_id.clone(),
                reason: Some(CouldNotRetrieveTranscriptReason::TranslationLanguageNotAvailable),
            });
        }

        let language = self
            .translation_languages_map
            .get(language_code)
            .unwrap()
            .clone();
        let url = format!("{}&tlang={}", self.url, language_code);

        Ok(Transcript::new(
            self.client.clone(),
            self.video_id.clone(),
            url,
            language,
            language_code.to_string(),
            true,
            vec![],
        ))
    }

    /// Returns the full human-readable language name of this transcript.
    ///
    /// # Returns
    ///
    /// * `&str` - The language name (e.g., "English", "EspaƱol")
    pub fn language(&self) -> &str {
        &self.language
    }

    /// Returns the language code of this transcript.
    ///
    /// # Returns
    ///
    /// * `&str` - The language code (e.g., "en", "es", "fr-CA")
    pub fn language_code(&self) -> &str {
        &self.language_code
    }

    /// Checks if this transcript was automatically generated by YouTube.
    ///
    /// # Returns
    ///
    /// * `bool` - `true` if automatically generated, `false` if manually created
    pub fn is_generated(&self) -> bool {
        self.is_generated
    }
}

impl fmt::Display for Transcript {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let translation_desc = if self.is_translatable() {
            "[TRANSLATABLE]"
        } else {
            ""
        };
        write!(
            f,
            "{} ({}){}",
            self.language_code, self.language, translation_desc
        )
    }
}