🎥 Make videos programmatically with React
parse srt
Jonny Burger09c973f347d3
diff --git a/packages/captions/package.json b/packages/captions/package.jsonindex f2352f7501..ae59afaed6 100644--- a/packages/captions/package.json+++ b/packages/captions/package.json@@ -24,9 +24,7 @@"peerDependencies": {},"devDependencies": {},"keywords": [- "remotion",- "openai",- "whisper"+ "remotion"],"publishConfig": {"access": "public"diff --git a/packages/captions/src/create-tiktok-style-captions.ts b/packages/captions/src/create-tiktok-style-captions.tsindex ca4e2d154c..afeefe7928 100644--- a/packages/captions/src/create-tiktok-style-captions.ts+++ b/packages/captions/src/create-tiktok-style-captions.ts@@ -13,19 +13,19 @@ export type TikTokPage = {};export function createTikTokStyleCaptions({- transcription,+ captions,combineTokensWithinMilliseconds,}: {- transcription: Caption[];+ captions: Caption[];combineTokensWithinMilliseconds: number;-}): {captions: TikTokPage[]} {- const merged: TikTokPage[] = [];+}): {pages: TikTokPage[]} {+ const tikTokStyleCaptions: TikTokPage[] = [];let currentText = '';let currentTokens: TikTokToken[] = [];let currentFrom = 0;let currentTo = 0;- transcription.forEach((item, index) => {+ captions.forEach((item, index) => {const {text} = item;// If text starts with a space, push the currentText (if it exists) and start a new oneif (@@ -33,7 +33,7 @@ export function createTikTokStyleCaptions({currentTo - currentFrom > combineTokensWithinMilliseconds) {if (currentText !== '') {- merged.push({+ tikTokStyleCaptions.push({text: currentText.trimStart(),startMs: currentFrom,tokens: currentTokens,@@ -68,8 +68,8 @@ export function createTikTokStyleCaptions({}// Ensure the last sentence is added- if (index === transcription.length - 1 && currentText !== '') {- merged.push({+ if (index === captions.length - 1 && currentText !== '') {+ tikTokStyleCaptions.push({text: currentText,startMs: currentFrom,tokens: currentTokens,@@ -77,5 +77,5 @@ export function createTikTokStyleCaptions({}});- return {captions: merged};+ return {pages: tikTokStyleCaptions};}diff --git a/packages/captions/src/index.ts b/packages/captions/src/index.tsindex aa44cbe73e..2512290121 100644--- a/packages/captions/src/index.ts+++ b/packages/captions/src/index.ts@@ -4,3 +4,4 @@ export {TikTokToken,createTikTokStyleCaptions,} from './create-tiktok-style-captions';+export {ParsedSrt, ParsedSrtLine, parseSrt} from './parse-srt';diff --git a/packages/captions/src/parse-srt.ts b/packages/captions/src/parse-srt.tsnew file mode 100644index 0000000000..4dcb6d9071--- /dev/null+++ b/packages/captions/src/parse-srt.ts@@ -0,0 +1,75 @@+export type ParsedSrtLine = {+ index: number;+ text: string;+ startInSeconds: number;+ endInSeconds: number;+};++export type ParsedSrt = ParsedSrtLine[];++function toSeconds(time: string) {+ const [first, second, third] = time.split(':');+ if (!first) {+ throw new Error(`Invalid timestamp:${time}`);+ }+ if (!second) {+ throw new Error(`Invalid timestamp:${time}`);+ }+ if (!third) {+ throw new Error(`Invalid timestamp:${time}`);+ }++ const [seconds, millis] = third.split(',');+ if (!seconds) {+ throw new Error(`Invalid timestamp:${time}`);+ }+ if (!millis) {+ throw new Error(`Invalid timestamp:${time}`);+ }++ return (+ parseInt(first, 10) * 3600 ++ parseInt(second, 10) * 60 ++ parseInt(seconds, 10) ++ parseInt(millis, 10) / 1000+ );+}++export type ParseSrtInput = {+ input: string;+};++export type ParseSrtOutput = {+ lines: ParsedSrt;+};++export const parseSrt = ({input}: ParseSrtInput): ParseSrtOutput => {+ const inputLines = input.split('\n');+ const lines: ParsedSrtLine[] = [];++ for (let i = 0; i < inputLines.length; i++) {+ const line = inputLines[i];+ const nextLine = inputLines[i + 1];+ if (line?.match(/([0-9]+)/) && nextLine?.includes(' --> ')) {+ const nextLineSplit = nextLine.split(' --> ');+ const start = toSeconds(nextLineSplit[0] as string);+ const end = toSeconds(nextLineSplit[1] as string);+ lines.push({+ index: Number(line),+ text: '',+ startInSeconds: start,+ endInSeconds: end,+ });+ } else if (line?.includes(' --> ')) {+ continue;+ } else if (line?.trim() === '') {+ (lines[lines.length - 1] as ParsedSrtLine).text = (+ lines[lines.length - 1] as ParsedSrtLine+ ).text.trim();+ } else {+ (lines[lines.length - 1] as ParsedSrtLine).text += line + '\n';+ }+ }++ return {lines};+};diff --git a/packages/captions/src/test/srt.test.ts b/packages/captions/src/test/srt.test.tsnew file mode 100644index 0000000000..5adfc24062--- /dev/null+++ b/packages/captions/src/test/srt.test.ts@@ -0,0 +1,102 @@+import {expect, test} from 'bun:test';+import {parseSrt} from '../parse-srt';++const input = `++1+00:00:00,000 --> 00:00:02,500+Welcome to the Example Subtitle File!++2+00:00:03,000 --> 00:00:06,000+This is a demonstration of SRT subtitles.++3+00:00:07,000 --> 00:00:10,500+You can use SRT files to add subtitles to your videos.++4+00:00:12,000 --> 00:00:15,000+Each subtitle entry consists of a number, a timecode,+and the subtitle text.++5+00:00:16,000 --> 00:00:20,000+The timecode format is hours:minutes:seconds,milliseconds.++6+00:00:21,000 --> 00:00:25,000+You can adjust the timing to match your video.++7+00:00:26,000 --> 00:00:30,000+Make sure the subtitle text is clear and readable.++8+00:00:31,000 --> 00:00:35,000+And that's how you create an SRT subtitle file!++9+00:00:36,000 --> 00:00:40,000+Enjoy adding subtitles to your videos!+`.trim();++test('Should create captions', () => {+ const {lines} = parseSrt({input});+ expect(lines).toEqual([+ {+ endInSeconds: 2.5,+ index: 1,+ startInSeconds: 0,+ text: 'Welcome to the Example Subtitle File!',+ },+ {+ endInSeconds: 6,+ index: 2,+ startInSeconds: 3,+ text: 'This is a demonstration of SRT subtitles.',+ },+ {+ endInSeconds: 10.5,+ index: 3,+ startInSeconds: 7,+ text: 'You can use SRT files to add subtitles to your videos.',+ },+ {+ endInSeconds: 15,+ index: 4,+ startInSeconds: 12,+ text: 'Each subtitle entry consists of a number, a timecode,\nand the subtitle text.',+ },+ {+ endInSeconds: 20,+ index: 5,+ startInSeconds: 16,+ text: 'The timecode format is hours:minutes:seconds,milliseconds.',+ },+ {+ endInSeconds: 25,+ index: 6,+ startInSeconds: 21,+ text: 'You can adjust the timing to match your video.',+ },+ {+ endInSeconds: 30,+ index: 7,+ startInSeconds: 26,+ text: 'Make sure the subtitle text is clear and readable.',+ },+ {+ endInSeconds: 35,+ index: 8,+ startInSeconds: 31,+ text: "And that's how you create an SRT subtitle file!",+ },+ {+ endInSeconds: 40,+ index: 9,+ startInSeconds: 36,+ text: 'Enjoy adding subtitles to your videos!\n',+ },+ ]);+});diff --git a/packages/captions/src/test/tiktok.test.ts b/packages/captions/src/test/tiktok.test.tsnew file mode 100644index 0000000000..3511637a7d--- /dev/null+++ b/packages/captions/src/test/tiktok.test.ts@@ -0,0 +1,75 @@+import {expect, test} from 'bun:test';+import {Caption} from '../captions';+import {createTikTokStyleCaptions} from '../create-tiktok-style-captions';++const captions: Caption[] = [+ {+ text: 'Using',+ startMs: 40,+ endMs: 300,+ timestampMs: 200,+ confidence: 0.948258,+ },+ {+ text: " Remotion's",+ startMs: 300,+ endMs: 900,+ timestampMs: 440,+ confidence: 0.548411,+ },+ {+ text: ' TikTok',+ startMs: 900,+ endMs: 1260,+ timestampMs: 1080,+ confidence: 0.953265,+ },+ {+ text: ' template,',+ startMs: 1260,+ endMs: 1950,+ timestampMs: 1600,+ confidence: 0.968126,+ },+];++test('Should create captions', () => {+ const {pages: tikTokStyleCaptions} = createTikTokStyleCaptions({+ captions,+ combineTokensWithinMilliseconds: 500,+ });+ expect(tikTokStyleCaptions).toEqual([+ {+ text: "Using Remotion's",+ startMs: 40,+ tokens: [+ {+ text: 'Using',+ fromMs: 40,+ toMs: 300,+ },+ {+ text: " Remotion's",+ fromMs: 300,+ toMs: 900,+ },+ ],+ },+ {+ text: 'TikTok template,',+ startMs: 900,+ tokens: [+ {+ text: 'TikTok',+ fromMs: 900,+ toMs: 1260,+ },+ {+ text: ' template,',+ fromMs: 1260,+ toMs: 1950,+ },+ ],+ },+ ]);+});diff --git a/packages/docs/docs/captions/caption.mdx b/packages/docs/docs/captions/caption.mdxnew file mode 100644index 0000000000..168bd60ed9--- /dev/null+++ b/packages/docs/docs/captions/caption.mdx@@ -0,0 +1,19 @@+---+title: Caption+crumb: '@remotion/captions'+---++# Caption<AvailableFrom v="4.0.216 "/>++This is a simple data structure for a caption.++```tsx twoslash+import {Caption} from '@remotion/captions';+// ^?+```++By establishing a standard data structure, we allow many operations that involve captions to be interoperable:++- Transcribing (using the [`@remotion/install-whisper-cpp`](/docs/install-whisper-cpp) package)+- Formatting (for example, creating pages using [`createTikTokStyleCaptions()`](/docs/captions/create-tiktok-style-captions))+- Serializing (for example to a .srt file)diff --git a/packages/docs/docs/captions/create-tiktok-style-captions.mdx b/packages/docs/docs/captions/create-tiktok-style-captions.mdxnew file mode 100644index 0000000000..479d194b64--- /dev/null+++ b/packages/docs/docs/captions/create-tiktok-style-captions.mdx@@ -0,0 +1,120 @@+---+title: createTikTokStyleCaptions()+crumb: '@remotion/captions'+---++# createTikTokStyleCaptions()<AvailableFrom v="4.0.216 "/>++Using this function, you can segment tokens to create "pages" of captions, as commonly seen on TikTok videos.++You may specify how often pages switch.+A high value for `combineTokensWithinMilliseconds` will fit many words on 1 page, while a low value will lead to word-by-word animation.++This function is safe to use in the browser, Node.js and Bun.++```tsx twoslash title="Create pages from captions"+import {createTikTokStyleCaptions, Caption} from '@remotion/captions';++const captions: Caption[] = [+ {+ text: 'Using',+ startMs: 40,+ endMs: 300,+ timestampMs: 200,+ confidence: null,+ },+ {+ text: " Remotion's",+ startMs: 300,+ endMs: 900,+ timestampMs: 440,+ confidence: null,+ },+ {+ text: ' TikTok',+ startMs: 900,+ endMs: 1260,+ timestampMs: 1080,+ confidence: null,+ },+ {+ text: ' template,',+ startMs: 1260,+ endMs: 1950,+ timestampMs: 1600,+ confidence: null,+ },+];++const {pages} = createTikTokStyleCaptions({+ captions,+ combineTokensWithinMilliseconds: 1200,+});++/* pages: [+ {+ text: "Using Remotion's",+ startMs: 40,+ tokens: [+ {+ text: 'Using',+ fromMs: 40,+ toMs: 300,+ },+ {+ text: " Remotion's",+ fromMs: 300,+ toMs: 900,+ },+ ],+ },+ {+ text: 'TikTok template,',+ startMs: 900,+ tokens: [+ {+ text: 'TikTok',+ fromMs: 900,+ toMs: 1260,+ },+ {+ text: ' template,',+ fromMs: 1260,+ toMs: 1950,+ },+ ],+ }+] */+```++## API++### `captions`++An array of `Caption` objects.++### `combineTokensWithinMilliseconds`++Words that are closer than this value will be combined into a single page.++## Return value++An object with the following properties:++### `pages`++An array of `TikTokPage` objects.++A page consists of:++- `text`: The text of the page.+- `startMs`: The start time of the page in milliseconds.+- `tokens`: An array of objects, if you want to animate word-per-word:+ - `text`: The text of the token.+ - `fromMs`: The absolute start time of the token in milliseconds.+ - `toMs`: The absolute end time of the token in milliseconds.++## See also++- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/captions/src/create-tiktok-style-captions.ts)+- [`@remotion/captions`](/docs/captions)diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.jsindex 672986f3cf..64f420511b 100644--- a/packages/docs/sidebars.js+++ b/packages/docs/sidebars.js@@ -574,7 +574,7 @@ module.exports = {type: 'doc',id: 'captions/index',},- items: [],+ items: ['captions/caption', 'captions/create-tiktok-style-captions'],},{type: 'category',diff --git a/packages/install-whisper-cpp/src/index.ts b/packages/install-whisper-cpp/src/index.tsindex 9e406d3292..9cacf21fb0 100644--- a/packages/install-whisper-cpp/src/index.ts+++ b/packages/install-whisper-cpp/src/index.ts@@ -1,9 +1,9 @@-export {convert} from './convert';export {Caption, convertToCaptions} from './convert-to-captions';export type {OnProgress} from './download';export {WhisperModel, downloadWhisperModel} from './download-whisper-model';export {installWhisperCpp} from './install-whisper-cpp';export type {Language} from './languages';+export {toCaptions} from './to-captions';export {TranscribeOnProgress,TranscriptionJson,diff --git a/packages/install-whisper-cpp/src/convert.ts b/packages/install-whisper-cpp/src/to-captions.tssimilarity index 83%rename from packages/install-whisper-cpp/src/convert.tsrename to packages/install-whisper-cpp/src/to-captions.tsindex 5cb24c21b6..dec955e1c2 100644--- a/packages/install-whisper-cpp/src/convert.ts+++ b/packages/install-whisper-cpp/src/to-captions.ts@@ -1,15 +1,15 @@import type {Caption} from '@remotion/captions';import type {TranscriptionJson} from './transcribe';-type ConvertInput = {+type ToCaptionsInput = {whisperCppOutput: TranscriptionJson<true>;};-type ConvertOutput = {+type ToCaptionsOutput = {captions: Caption[];};-export const convert = (input: ConvertInput): ConvertOutput => {+export const toCaptions = (input: ToCaptionsInput): ToCaptionsOutput => {const {transcription} = input.whisperCppOutput;const captions: Caption[] = [];diff --git a/packages/template-tiktok/sub.mjs b/packages/template-tiktok/sub.mjsindex 34dcabc578..96216fc636 100644--- a/packages/template-tiktok/sub.mjs+++ b/packages/template-tiktok/sub.mjs@@ -18,7 +18,7 @@ import {downloadWhisperModel,installWhisperCpp,transcribe,- convert,+ toCaptions,} from "@remotion/install-whisper-cpp";const extractToTempAudioFile = (fileToTranscribe, tempOutFile) => {@@ -48,7 +48,7 @@ const subFile = async (filePath, fileName, folder) => {splitOnWord: true,});- const { captions } = convert({+ const { captions } = toCaptions({whisperCppOutput,});writeFileSync(