Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Machine Translated Subtitles to YouTube #609

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions extension/src/pages/youtube-page.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { VideoData } from '@project/common';
import { trackFromDef } from './util';

const TLANG = 'ja';

declare global {
interface Window {
trustedTypes?: any;
Expand Down Expand Up @@ -37,6 +39,29 @@ const adaptYtTrack = (track: any) => {
});
};

const appendTranslatedTracks = (tracks: any, tlang: string) => {
const translatedTracks = [...tracks];

for (const track of tracks) {
// Ignore subtitles that are already in the target language
if (track.languageCode !== tlang) {
const translatedTrack = {
...track,
name: {
simpleText: `${track.name?.simpleText} >> ${tlang}`,
runs: track.name?.runs?.map((run: any) => ({ ...run, text: `${run.text} >> ${tlang}` })),
},
languageCode: tlang,
baseUrl: `${track.baseUrl}&tlang=${tlang}`, // YouTube API param for translation
};

translatedTracks.push(translatedTrack);
}
}

return translatedTracks;
};

document.addEventListener(
'asbplayer-get-synced-data',
async () => {
Expand Down Expand Up @@ -89,9 +114,10 @@ document.addEventListener(
}

response.basename = playerContext.videoDetails?.title || document.title;
response.subtitles = (playerContext?.captions?.playerCaptionsTracklistRenderer?.captionTracks || []).map(
adaptYtTrack
);
response.subtitles = appendTranslatedTracks(
playerContext?.captions?.playerCaptionsTracklistRenderer?.captionTracks || [],
TLANG
).map(adaptYtTrack);
} catch (error) {
if (error instanceof Error) {
response.error = error.message;
Expand Down Expand Up @@ -137,7 +163,7 @@ JSON.parse = function () {

if (typeof tracks === 'object' && Array.isArray(tracks) && typeof value?.videoDetails?.videoId === 'string') {
const videoId = value.videoDetails.videoId;
const subtitles = tracks.map(adaptYtTrack);
const subtitles = appendTranslatedTracks(tracks, TLANG).map(adaptYtTrack);
const basename = value.videoDetails?.title || document.title;
dataByVideoId[videoId] = {
subtitles,
Expand Down