Skip to content

Commit e92b0f2

Browse files
committed
- Added support for auto-translated subtitles with auto_captions => 1.
When the config-option `auto_captions` is set to 1 and the auto-generated subtitle is not in a language that we want (specified in `srt_languages`), then we try to return a translated version of the auto-generated subtitle in a preferred language.
1 parent 906ace1 commit e92b0f2

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

lib/WWW/YoutubeViewer.pm

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -994,7 +994,16 @@ sub get_streaming_urls {
994994
my $caption_data = $self->parse_json_string($captions_json);
995995

996996
if (eval { ref($caption_data->{captions}{playerCaptionsTracklistRenderer}{captionTracks}) eq 'ARRAY' }) {
997+
997998
push @caption_urls, @{$caption_data->{captions}{playerCaptionsTracklistRenderer}{captionTracks}};
999+
1000+
my $translationLanguages = $caption_data->{captions}{playerCaptionsTracklistRenderer}{translationLanguages};
1001+
1002+
if (ref($translationLanguages) eq 'ARRAY') {
1003+
foreach my $caption (@caption_urls) {
1004+
$caption->{translationLanguages} = $translationLanguages;
1005+
}
1006+
}
9981007
}
9991008
}
10001009

lib/WWW/YoutubeViewer/GetCaption.pm

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,27 @@ sub find_caption_data {
122122
return $caption if defined($caption);
123123
}
124124

125+
# Return a translated subtitle (if available)
126+
if ($self->{auto_captions}) {
127+
foreach my $caption (@{$self->{captions}}) {
128+
129+
$caption->{isTranslatable} or next;
130+
exists($caption->{translationLanguages}) or next;
131+
ref($caption->{translationLanguages}) eq 'ARRAY' or next;
132+
133+
foreach my $lang (@{$self->{languages}}) {
134+
foreach my $trans_lang (@{$caption->{translationLanguages}}) {
135+
if ($trans_lang->{languageCode} =~ /^\Q$lang\E(?:\z|[_-])/i) {
136+
my %caption_copy = %{$caption};
137+
$caption_copy{languageCode} = $trans_lang->{languageCode};
138+
$caption_copy{baseUrl} .= "&tlang=$trans_lang->{languageCode}";
139+
return \%caption_copy;
140+
}
141+
}
142+
}
143+
}
144+
}
145+
125146
return;
126147
}
127148

0 commit comments

Comments
 (0)