Skip to content

🎥 Make videos programmatically with React

new function

Jonny Burgere6520478f644
diff --git a/packages/docs/components/TableOfContents/install-whisper-cpp.tsx b/packages/docs/components/TableOfContents/install-whisper-cpp.tsx
index 28db4a4b2a..ece8c535f4 100644
--- a/packages/docs/components/TableOfContents/install-whisper-cpp.tsx
+++ b/packages/docs/components/TableOfContents/install-whisper-cpp.tsx
@@ -18,6 +18,10 @@ export const TableOfContents: React.FC = () => {
<strong>transcribe()</strong>
<div>Transcribe an audio file</div>
</TOCItem>
+ <TOCItem link="/docs/install-whisper-cpp/convert-to-captions">
+ <strong>convertToCaptions()</strong>
+ <div>Postprocessing for TikTok-style captions</div>
+ </TOCItem>
</Grid>
</div>
);
diff --git a/packages/docs/docs/install-whisper-cpp/convert-to-captions.mdx b/packages/docs/docs/install-whisper-cpp/convert-to-captions.mdx
new file mode 100644
index 0000000000..1dcb3c7917
--- /dev/null
+++ b/packages/docs/docs/install-whisper-cpp/convert-to-captions.mdx
@@ -0,0 +1,109 @@
+---
+image: /generated/articles-docs-install-whisper-cpp-convert-to-captions.png
+title: convertToCaptions()
+crumb: "@remotion/install-whisper-cpp"
+---
+
+# transcribe()<AvailableFrom v="4.0.131 "/>
+
+Opinionated function that converts the output from [`transcribe()`](/docs/install-whisper-cpp/transcribe) into easily digestable captions.
+Can also combine words with close timestamps.
+Useful for TikTok/Reel-type of videos that animate captions word-by-word.
+
+```tsx twoslash title="transcribe.mjs"
+// @module: esnext
+// @target: es2022
+import path from "path";
+import { transcribe, convertToCaptions } from "@remotion/install-whisper-cpp";
+
+const { transcription } = await transcribe({
+ inputPath: "/path/to/audio.wav",
+ whisperPath: path.join(process.cwd(), "whisper.cpp"),
+ model: "base.en",
+ tokenLevelTimestamps: true,
+});
+
+const { captions } = convertToCaptions({
+ transcription,
+ combineTokensWithinMilliseconds: 200,
+});
+
+for (const line of captions) {
+ console.log(line.text, line.startInSeconds);
+}
+```
+
+## Options
+
+### `transcription`
+
+The `transcription` object that you retrieved from [`transcribe()`](/docs/install-whisper-cpp).
+The `tokenLevelTimestamps` option must have been set to `true`.
+
+### `combineTokensWithinMilliseconds`
+
+Combine words that are close to each other.
+If words are not combined, they might display for a very short time if word-by-word captions are being used.
+Disable combination by setting `0`.
+Recommendation: `200`.
+
+## Return value
+
+An array with objects of the following shape:
+
+```ts twoslash
+type Caption = {
+ text: string;
+ startInSeconds: number;
+};
+```
+
+## Suggested usage
+
+This shows how, given a data structure produced by `convertToCaptions()`, word-by-word captions can be rendered in a Remotion project.
+See our [TikTok template](/templates/tiktok) for a full reference implementation.
+
+:::note
+`@remotion/install-whisper-cpp` cannot be imported on the frontend, it is a Node.js API.
+Only the TypeScript type is imported in this example
+:::
+
+```tsx twoslash
+const Subtitle: React.FC<{ text: string }> = () => null;
+// ---cut---
+import type { Caption } from "@remotion/install-whisper-cpp";
+import { Sequence, useVideoConfig } from "remotion";
+
+const Captions: React.FC<{
+ subtitles: Caption[];
+}> = ({ subtitles }) => {
+ const { fps } = useVideoConfig();
+
+ return (
+ <>
+ {subtitles.map((subtitle, index) => {
+ const nextSubtitle = subtitles[index + 1] ?? null;
+ const subtitleStartFrame = subtitle.startInSeconds * fps;
+ const subtitleEndFrame = Math.min(
+ nextSubtitle ? nextSubtitle.startInSeconds * fps : Infinity,
+ subtitleStartFrame + fps,
+ );
+
+ return (
+ <Sequence
+ from={subtitleStartFrame}
+ durationInFrames={subtitleEndFrame - subtitleStartFrame}
+ >
+ <Subtitle key={index} text={subtitle.text} />;
+ </Sequence>
+ );
+ })}
+ </>
+ );
+};
+```
+
+## See also
+
+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/install-whisper-cpp/src/convert-to-captions.ts)
+- [`@remotion/install-whisper-cpp`](/docs/install-whisper-cpp)
diff --git a/packages/docs/docs/install-whisper-cpp/transcribe.mdx b/packages/docs/docs/install-whisper-cpp/transcribe.mdx
index 18b9f082fa..372b716d39 100644
--- a/packages/docs/docs/install-whisper-cpp/transcribe.mdx
+++ b/packages/docs/docs/install-whisper-cpp/transcribe.mdx
@@ -19,6 +19,7 @@ const { transcription } = await transcribe({
inputPath: "/path/to/audio.wav",
whisperPath: path.join(process.cwd(), "whisper.cpp"),
model: "base.en",
+ tokenLevelTimestamps: true,
});
for (const token of transcription) {
@@ -81,8 +82,8 @@ _optional - default: false_
Set this boolean flag if you want to get a translated transcription of the provided file in English.
Make sure to not use a \*.en model, as they will not be able to translate a foreign language to english.
-:::info
-We recommend using at least the `medium` model to get satisfactory results.
+:::note
+We recommend using at least the `medium` model to get satisfactory results when translating.
:::
## Return value
@@ -92,18 +93,35 @@ We recommend using at least the `medium` model to get satisfactory results.
An object containing all the metadata and transcriptions resulting from the transcription process.
```ts twoslash
+type Timestamps = {
+ from: string;
+ to: string;
+};
+
+type Offsets = {
+ from: number;
+ to: number;
+};
+
+type WordLevelToken = {
+ t_dtw: number;
+ text: string;
+ timestamps: Timestamps;
+ offsets: Offsets;
+ id: number;
+ p: number;
+};
+
type TranscriptionItem = {
- timestamps: {
- from: string;
- to: string;
- };
- offsets: {
- from: number;
- to: number;
- };
+ timestamps: Timestamps;
+ offsets: Offsets;
text: string;
};
+type TranscriptionItemWithTimestamp = TranscriptionItem & {
+ tokens: WordLevelToken[];
+};
+
type Model = {
type: string;
multilingual: boolean;
@@ -124,24 +142,34 @@ type Model = {
ftype: number;
};
-type TranscriptionJson = {
+type Params = {
+ model: string;
+ language: string;
+ translate: boolean;
+};
+
+type Result = {
+ language: string;
+};
+
+export type TranscriptionJson<WithTokenLevelTimestamp extends boolean> = {
systeminfo: string;
model: Model;
- params: {
- model: string;
- language: string;
- translate: boolean;
- };
- result: {
- language: string;
- };
- transcription: TranscriptionItem[];
+ params: Params;
+ result: Result;
+ transcription: true extends WithTokenLevelTimestamp
+ ? TranscriptionItemWithTimestamp[]
+ : TranscriptionItem[];
};
```
+Prefer relying on the `t_dtw` value for accurate timestamps over `offsets`.
+Use [`convertToCaptions()`](/docs/install-whisper-cpp/convert-to-captions) to use our opinionated suggestion for postprocessing the captions.
+
## See also
- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/install-whisper-cpp/src/transcribe.ts)
- [`@remotion/install-whisper-cpp`](/docs/install-whisper-cpp)
+- [`convertToCaptions()`](/docs/install-whisper-cpp/convert-to-captions)
- [`downloadWhisperModel()`](/docs/install-whisper-cpp/download-whisper-model)
- [`installWhisperCpp()`](/docs/install-whisper-cpp/install-whisper-cpp)
diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.js
index cce499274d..464856bf95 100644
--- a/packages/docs/sidebars.js
+++ b/packages/docs/sidebars.js
@@ -502,6 +502,7 @@ module.exports = {
"install-whisper-cpp/install-whisper-cpp",
"install-whisper-cpp/download-whisper-model",
"install-whisper-cpp/transcribe",
+ "install-whisper-cpp/convert-to-captions",
],
},
],
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index 861000e9b1..b52b4e740a 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -860,6 +860,13 @@ export const articles = [
compId: "articles-docs-importing-assets",
crumb: "How To",
},
+ {
+ id: "install-whisper-cpp/convert-to-captions",
+ title: "convertToCaptions()",
+ relativePath: "docs/install-whisper-cpp/convert-to-captions.mdx",
+ compId: "articles-docs-install-whisper-cpp-convert-to-captions",
+ crumb: "@remotion/install-whisper-cpp",
+ },
{
id: "install-whisper-cpp/download-whisper-model",
title: "downloadWhisperModel()",
diff --git a/packages/docs/static/generated/articles-docs-install-whisper-cpp-convert-to-captions.png b/packages/docs/static/generated/articles-docs-install-whisper-cpp-convert-to-captions.png
new file mode 100644
index 0000000000..e0f3f19258
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-install-whisper-cpp-convert-to-captions.png differ
diff --git a/packages/install-whisper-cpp/src/convert-to-captions.ts b/packages/install-whisper-cpp/src/convert-to-captions.ts
index 02146178fa..e261b0d1f2 100644
--- a/packages/install-whisper-cpp/src/convert-to-captions.ts
+++ b/packages/install-whisper-cpp/src/convert-to-captions.ts
@@ -6,11 +6,11 @@ export type Caption = {
};
export function convertToCaptions({
- transcriptions,
- combineCloseWords,
+ transcription,
+ combineTokensWithinMilliseconds,
}: {
- transcriptions: TranscriptionJson<true>['transcription'];
- combineCloseWords: number;
+ transcription: TranscriptionJson<true>['transcription'];
+ combineTokensWithinMilliseconds: number;
}): {captions: Caption[]} {
const merged: Caption[] = [];
let currentText = '';
@@ -18,10 +18,13 @@ export function convertToCaptions({
let currentTo = 0;
let currentTokenLevelTimestamp = 0;
- transcriptions.forEach((item, index) => {
+ transcription.forEach((item, index) => {
const {text} = item;
// If text starts with a space, push the currentText (if it exists) and start a new one
- if (text.startsWith(' ') && currentTo - currentFrom > combineCloseWords) {
+ if (
+ text.startsWith(' ') &&
+ currentTo - currentFrom > combineTokensWithinMilliseconds
+ ) {
if (currentText !== '') {
merged.push({
text: currentText,
@@ -48,7 +51,7 @@ export function convertToCaptions({
}
// Ensure the last sentence is added
- if (index === transcriptions.length - 1 && currentText !== '') {
+ if (index === transcription.length - 1 && currentText !== '') {
merged.push({
text: currentText,
startInSeconds: currentTokenLevelTimestamp / 100,
diff --git a/packages/install-whisper-cpp/src/test/convert-to-captions.test.ts b/packages/install-whisper-cpp/src/test/convert-to-captions.test.ts
index e4d9335e99..cca17e1ba1 100644
--- a/packages/install-whisper-cpp/src/test/convert-to-captions.test.ts
+++ b/packages/install-whisper-cpp/src/test/convert-to-captions.test.ts
@@ -4,8 +4,8 @@ import {examplePayload} from './example-payload';
test('Convert to captions - 200ms together', () => {
const {captions: transcript} = convertToCaptions({
- transcriptions: examplePayload.transcription,
- combineCloseWords: 200,
+ transcription: examplePayload.transcription,
+ combineTokensWithinMilliseconds: 200,
});
expect(transcript).toEqual([
@@ -123,8 +123,8 @@ test('Convert to captions - 200ms together', () => {
test('Convert to captions - 0ms together', () => {
const {captions: transcript} = convertToCaptions({
- transcriptions: examplePayload.transcription,
- combineCloseWords: 0,
+ transcription: examplePayload.transcription,
+ combineTokensWithinMilliseconds: 0,
});
expect(transcript).toEqual([