Skip to content

🎥 Make videos programmatically with React

Fix OpenAI Whisper apostrophe variant parsing (#7317)

Jonny Burgere6f6437e80f4
diff --git a/packages/openai-whisper/src/openai-whisper-api-to-captions.ts b/packages/openai-whisper/src/openai-whisper-api-to-captions.ts
index dc122ca797..60809ce5aa 100644
--- a/packages/openai-whisper/src/openai-whisper-api-to-captions.ts
+++ b/packages/openai-whisper/src/openai-whisper-api-to-captions.ts
@@ -9,6 +9,23 @@ export type OpenAiToCaptionsOutput = {
captions: Caption[];
};
+const escapeRegex = (text: string) => {
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+};
+
+const apostropheVariants = ['\u0027', '\u2018', '\u2019', '\u02bc', '\uff07'];
+const apostropheVariantRegex = `[${apostropheVariants.map(escapeRegex).join('')}]`;
+
+const escapeWordForRegex = (text: string) => {
+ return Array.from(text)
+ .map((character) => {
+ return apostropheVariants.includes(character)
+ ? apostropheVariantRegex
+ : escapeRegex(character);
+ })
+ .join('');
+};
+
export const openAiWhisperApiToCaptions = ({
transcription,
}: OpenAiToCaptionsInput): OpenAiToCaptionsOutput => {
@@ -36,9 +53,10 @@ export const openAiWhisperApiToCaptions = ({
word.word = word.word.trimStart();
}
- const punctuation = `\\?,\\.\\%\\–\\!\\;\\:\\'\\"\\-\\_\\(\\)\\[\\]\\{\\}\\@\\#\\$\\^\\&\\*\\+\\=\\/\\|\\<\\>\\~\``;
+ const punctuation = `\\?,\\.\\%\\–\\!\\;\\:\\'\\"\\-\\_\\(\\)\\[\\]\\{\\}\\@\\#\\$\\^\\&\\*\\+\\=\\/\\|\\<\\>\\~\`\\u2018\\u2019\\u02bc\\uff07`;
+ const wordToMatch = word.word.replace(new RegExp(`^[${punctuation}]+`), '');
const match = new RegExp(
- `^([\\s?${punctuation}]{0,4})${word.word.replace(new RegExp(`^[${punctuation}]+`), '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([${punctuation}]{0,3})?`,
+ `^([\\s?${punctuation}]{0,4})${escapeWordForRegex(wordToMatch)}([${punctuation}]{0,3})?`,
).exec(remainingText);
if (!match) {
throw new Error(
diff --git a/packages/openai-whisper/src/test/regressions.test.ts b/packages/openai-whisper/src/test/regressions.test.ts
index ba18b7fa6e..2863b69365 100644
--- a/packages/openai-whisper/src/test/regressions.test.ts
+++ b/packages/openai-whisper/src/test/regressions.test.ts
@@ -128,3 +128,43 @@ test('Regression test 2', () => {
},
]);
});
+
+test('Issue 7298 - apostrophe variants', () => {
+ expect(
+ openAiWhisperApiToCaptions({
+ transcription: {
+ task: 'transcribe',
+ text: " Let's go!",
+ words: [
+ {
+ start: 0,
+ end: 0.1,
+ word: 'Let’s',
+ },
+ {
+ start: 0.1,
+ end: 0.2,
+ word: 'go',
+ },
+ ],
+ duration: 0.2,
+ language: 'english',
+ },
+ }).captions,
+ ).toEqual([
+ {
+ confidence: null,
+ endMs: 100,
+ startMs: 0,
+ text: " Let's",
+ timestampMs: 50,
+ },
+ {
+ confidence: null,
+ endMs: 200,
+ startMs: 100,
+ text: ' go!',
+ timestampMs: 150.00000000000003,
+ },
+ ]);
+});