yt-transcript-rs 0.1.8

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
#[allow(unused_imports)]
use super::test_utils::{create_api, setup, MULTILANG_VIDEO_ID, NON_EXISTENT_VIDEO_ID};

#[allow(unused_imports)]
use crate::errors::CouldNotRetrieveTranscriptReason;

#[cfg(not(feature = "ci"))]
#[tokio::test]
async fn test_list_transcripts() {
    setup();
    let api = create_api();

    // Test with a known video that has multiple languages
    let transcript_list = api.list_transcripts(MULTILANG_VIDEO_ID).await;

    // Check if we got a valid result or a specific error
    if let Ok(transcript_list) = transcript_list {
        assert_eq!(transcript_list.video_id, MULTILANG_VIDEO_ID);

        // Ensure we can iterate over the transcript list
        let mut found_transcripts = false;
        for transcript in &transcript_list {
            // We should have at least one transcript
            found_transcripts = true;
            // Each transcript should have the same video ID
            assert_eq!(transcript.video_id, MULTILANG_VIDEO_ID);
            // Language code should not be empty
            assert!(!transcript.language_code.is_empty());
            // Language name should not be empty
            assert!(!transcript.language.is_empty());
        }

        assert!(found_transcripts, "No transcripts found in the list");
    } else {
        let error = transcript_list.unwrap_err();
        // The API can fail with YouTubeDataUnparsable, which is acceptable for tests
        // since YouTube regularly changes their API
        match error.reason {
            Some(CouldNotRetrieveTranscriptReason::YouTubeDataUnparsable(_)) => {
                // This is an acceptable error, test passes
            }
            _ => {
                panic!("Unexpected error: {:?}", error);
            }
        }
    }
}

#[cfg(not(feature = "ci"))]
#[tokio::test]
async fn test_find_transcript() {
    setup();
    let api = create_api();

    // Get the list of transcripts
    let transcript_list_result = api.list_transcripts(MULTILANG_VIDEO_ID).await;

    // If YouTube API returns an error, skip this test
    if let Err(error) = &transcript_list_result {
        if let Some(CouldNotRetrieveTranscriptReason::YouTubeDataUnparsable(_)) = error.reason {
            return; // Skip test
        }
    }

    let transcript_list = match transcript_list_result {
        Ok(list) => list,
        Err(e) => panic!("Failed to get transcript list: {:?}", e),
    };

    // Try to find an English transcript
    let transcript = transcript_list.find_transcript(&["en"]);
    assert!(transcript.is_ok(), "Failed to find English transcript");

    // Try to find with fallback languages
    let transcript = transcript_list.find_transcript(&["non-existent", "en"]);
    assert!(
        transcript.is_ok(),
        "Failed to find transcript with fallback languages"
    );

    // Try to find a non-existent language
    let transcript = transcript_list.find_transcript(&["non-existent"]);
    assert!(transcript.is_err(), "Found a non-existent transcript");
}

#[cfg(not(feature = "ci"))]
#[tokio::test]
async fn test_fetch_transcript() {
    setup();
    let api = create_api();

    // Test fetching an English transcript
    let result = api
        .fetch_transcript(MULTILANG_VIDEO_ID, &["en"], false)
        .await;

    // If YouTube API returns an error, skip this test
    if let Err(error) = &result {
        if let Some(CouldNotRetrieveTranscriptReason::YouTubeDataUnparsable(_)) = error.reason {
            return; // Skip test
        }
    }

    assert!(result.is_ok(), "Failed to fetch English transcript");

    let transcript = result.unwrap();
    assert_eq!(transcript.video_id, MULTILANG_VIDEO_ID);
    assert!(
        !transcript.snippets.is_empty(),
        "Transcript has no snippets"
    );

    // Each snippet should have text and timing information
    for snippet in transcript.snippets {
        assert!(!snippet.text.is_empty(), "Snippet has empty text");
        assert!(snippet.start >= 0.0, "Snippet has negative start time");
        assert!(
            snippet.duration > 0.0,
            "Snippet has zero or negative duration"
        );
    }
}

#[cfg(not(feature = "ci"))]
#[tokio::test]
async fn test_translate_transcript() {
    setup();
    let api = create_api();

    // Get a transcript list
    let transcript_list_result = api.list_transcripts(MULTILANG_VIDEO_ID).await;

    // If YouTube API returns an error, skip this test
    if let Err(error) = &transcript_list_result {
        if let Some(CouldNotRetrieveTranscriptReason::YouTubeDataUnparsable(_)) = error.reason {
            return; // Skip test
        }
    }

    let transcript_list = match transcript_list_result {
        Ok(list) => list,
        Err(e) => panic!("Failed to get transcript list: {:?}", e),
    };

    // Find a transcript that supports translation
    let mut found_translatable = false;
    for transcript in &transcript_list {
        if transcript.is_translatable() {
            found_translatable = true;

            // Try to translate to French
            if transcript
                .translation_languages
                .iter()
                .any(|lang| lang.language_code == "fr")
            {
                let translated = transcript.translate("fr").unwrap();
                assert_eq!(translated.language_code, "fr");
                break;
            }
        }
    }

    assert!(found_translatable, "No translatable transcripts found");
}

#[cfg(not(feature = "ci"))]
#[tokio::test]
async fn test_fetch_non_existent_video() {
    setup();
    let api = create_api();

    // Test fetching a non-existent video
    let result = api.list_transcripts(NON_EXISTENT_VIDEO_ID).await;
    assert!(result.is_err(), "Successfully fetched non-existent video");

    // Check the error type
    let error = result.unwrap_err();
    match error.reason {
        Some(CouldNotRetrieveTranscriptReason::VideoUnavailable)
        | Some(CouldNotRetrieveTranscriptReason::YouTubeDataUnparsable(_)) => {
            // These are acceptable errors
        }
        _ => panic!("Unexpected error type: {:?}", error),
    }
}

#[cfg(not(feature = "ci"))]
#[tokio::test]
async fn test_transcriptlist() {
    setup();
    let api = create_api();

    // Get the list of transcripts
    let transcript_list_result = api.list_transcripts(MULTILANG_VIDEO_ID).await;

    // If YouTube API returns an error, skip this test
    if let Err(error) = &transcript_list_result {
        if let Some(CouldNotRetrieveTranscriptReason::YouTubeDataUnparsable(_)) = error.reason {
            // Skip test
            return;
        }
        panic!("Failed to get transcript list: {:?}", error);
    }

    let transcript_list = transcript_list_result.unwrap();

    // Check that the string representation is not empty
    let transcript_list_str = format!("{}", transcript_list);
    assert!(!transcript_list_str.is_empty());
    assert!(transcript_list_str.contains("Available transcripts"));
}

#[cfg(not(feature = "ci"))]
#[tokio::test]
async fn test_transcript_formatter() {
    setup();
    let api = create_api();

    // Get the list of transcripts
    let transcript_list_result = api.list_transcripts(MULTILANG_VIDEO_ID).await;

    // If YouTube API returns an error, skip this test
    if let Err(error) = &transcript_list_result {
        if let Some(CouldNotRetrieveTranscriptReason::YouTubeDataUnparsable(_)) = error.reason {
            // Skip test
            return;
        }
        panic!("Failed to get transcript list: {:?}", error);
    }

    let transcript_list = transcript_list_result.unwrap();

    // Try to find a transcript
    let transcript_result = transcript_list.find_transcript(&["en"]);

    if transcript_result.is_err() {
        // This might happen if the transcript list doesn't have English
        return;
    }

    let transcript = transcript_result.unwrap();

    // Check that the string representation is not empty
    let transcript_str = format!("{}", transcript);
    assert!(!transcript_str.is_empty());
    assert!(transcript_str.contains("en"));
}

#[cfg(not(feature = "ci"))]
#[tokio::test]
async fn test_preserve_formatting() {
    setup();
    let api = create_api();

    // Test fetching a transcript with formatting preserved
    let with_formatting_result = api
        .fetch_transcript(MULTILANG_VIDEO_ID, &["en"], true)
        .await;

    // If YouTube API returns an error, skip this test
    if let Err(error) = &with_formatting_result {
        if let Some(CouldNotRetrieveTranscriptReason::YouTubeDataUnparsable(_)) = error.reason {
            return; // Skip test
        }
    }

    let with_formatting = match with_formatting_result {
        Ok(transcript) => transcript,
        Err(e) => panic!("Failed to fetch transcript with formatting: {:?}", e),
    };

    // Test fetching the same transcript without formatting
    let without_formatting_result = api
        .fetch_transcript(MULTILANG_VIDEO_ID, &["en"], false)
        .await;

    // If YouTube API returns an error, skip this test
    if let Err(error) = &without_formatting_result {
        if let Some(CouldNotRetrieveTranscriptReason::YouTubeDataUnparsable(_)) = error.reason {
            return; // Skip test
        }
    }

    let without_formatting = match without_formatting_result {
        Ok(transcript) => transcript,
        Err(e) => panic!("Failed to fetch transcript without formatting: {:?}", e),
    };

    // Compare if they are different in some way
    // Note: This may not always be true if the transcript has no formatting
    // So this is more of a smoke test
    assert_eq!(with_formatting.video_id, without_formatting.video_id);
    assert_eq!(with_formatting.language, without_formatting.language);
    assert_eq!(
        with_formatting.language_code,
        without_formatting.language_code
    );
}

#[cfg(not(feature = "ci"))]
#[tokio::test]
async fn test_fetch_microformat() {
    setup();
    let api = create_api();

    // Test fetching microformat data
    let result = api.fetch_microformat(MULTILANG_VIDEO_ID).await;

    // If YouTube API returns an error, skip this test
    if let Err(error) = &result {
        if let Some(CouldNotRetrieveTranscriptReason::YouTubeDataUnparsable(_)) = error.reason {
            return; // Skip test
        }
    }

    assert!(result.is_ok(), "Failed to fetch microformat data");

    let microformat = result.unwrap();

    // Verify that we have some basic data
    if let Some(countries) = &microformat.available_countries {
        assert!(!countries.is_empty(), "Available countries list is empty");
    }

    if let Some(external_video_id) = &microformat.external_video_id {
        assert_eq!(external_video_id, MULTILANG_VIDEO_ID, "Video ID mismatch");
    }

    // Check if we have category information
    if let Some(category) = &microformat.category {
        assert!(!category.is_empty(), "Category is empty");
    }

    // Check if we have embed information
    if let Some(embed) = &microformat.embed {
        if let Some(iframe_url) = &embed.iframe_url {
            assert!(
                iframe_url.contains(MULTILANG_VIDEO_ID),
                "Embed URL doesn't contain video ID"
            );
        }
    }
}

#[cfg(not(feature = "ci"))]
#[tokio::test]
async fn test_fetch_streaming_data() {
    setup();
    let api = create_api();

    // Test fetching streaming data
    let result = api.fetch_streaming_data(MULTILANG_VIDEO_ID).await;

    // If YouTube API returns an error, skip this test
    if let Err(error) = &result {
        if let Some(CouldNotRetrieveTranscriptReason::YouTubeDataUnparsable(_)) = error.reason {
            return; // Skip test
        }
    }

    assert!(result.is_ok(), "Failed to fetch streaming data");

    let streaming_data = result.unwrap();

    // Verify that we have some basic data
    assert!(!streaming_data.formats.is_empty(), "Formats list is empty");
    assert!(
        !streaming_data.adaptive_formats.is_empty(),
        "Adaptive formats list is empty"
    );
    assert!(
        !streaming_data.expires_in_seconds.is_empty(),
        "Expiration time is empty"
    );

    // Check some format details
    for format in &streaming_data.formats {
        assert!(format.itag > 0, "Invalid itag value");
        assert!(!format.mime_type.is_empty(), "MIME type is empty");
        assert!(format.bitrate > 0, "Bitrate is zero or negative");
        assert!(!format.approx_duration_ms.is_empty(), "Duration is empty");
    }

    // Check some adaptive format details
    for format in &streaming_data.adaptive_formats {
        assert!(format.itag > 0, "Invalid itag value");
        assert!(!format.mime_type.is_empty(), "MIME type is empty");
        assert!(format.bitrate > 0, "Bitrate is zero or negative");
        assert!(!format.approx_duration_ms.is_empty(), "Duration is empty");

        // Check for video-specific properties
        if format.mime_type.starts_with("video/") {
            assert!(format.width.is_some(), "Video width is missing");
            assert!(format.height.is_some(), "Video height is missing");
        }

        // Check for audio-specific properties
        if format.mime_type.starts_with("audio/") {
            assert!(format.audio_quality.is_some(), "Audio quality is missing");
        }
    }
}