-
Notifications
You must be signed in to change notification settings - Fork 20
/
Subtitles.ts
568 lines (427 loc) · 15.7 KB
/
Subtitles.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
import { htmlToText } from 'html-to-text'
import { secondsToHMS, secondsToMS } from '../utilities/Utilities.js'
import { isWordOrSymbolWord } from '../nlp/Segmentation.js'
import { charactersToWriteAhead } from '../audio/AudioPlayer.js'
import { Timeline, TimelineEntry } from '../utilities/Timeline.js'
import { readFileAsUtf8 } from '../utilities/FileSystem.js'
import { deepClone } from '../utilities/ObjectUtilities.js'
import { formatHMS, formatMS, startsWithAnyOf } from '../utilities/StringUtilities.js'
export async function subtitlesFileToText(filename: string) {
return subtitlesToText(await readFileAsUtf8(filename))
}
export function subtitlesToText(subtitles: string) {
return subtitlesToTimeline(subtitles, true).map(entry => entry.text).join(' ')
}
export function subtitlesToTimeline(subtitles: string, removeMarkup = true) {
const lines = subtitles.split(/\r?\n/)
const timeline: Timeline = []
let isWithinCue = false
// Parse lines of subtitles text
for (let line of lines) {
line = line.trim()
if (line.length == 0) {
isWithinCue = false
continue
}
let result = tryParseTimeRangePatternWithHours(line)
if (!result.succeeded) {
result = tryParseTimeRangePatternWithoutHours(line)
}
if (result.succeeded) {
timeline.push({
type: 'segment',
startTime: result.startTime,
endTime: result.endTime,
text: ''
})
isWithinCue = true
} else if (isWithinCue && timeline.length > 0) {
const lastEntry = timeline[timeline.length - 1]
if (lastEntry.text == '') {
lastEntry.text = line
} else {
lastEntry.text += ' ' + line
}
}
}
if (!removeMarkup) {
return timeline
}
// Remove markup in each entry text
const timelineWithoutMarkup = timeline.map((entry) => {
let plainText: string = entry.text
plainText = plainText.replaceAll(/<[^>]*>/g, '')
plainText = htmlToText(plainText, { wordwrap: false })
plainText = plainText.replaceAll(/\s+/g, ' ').trim()
return { ...entry, text: plainText }
})
return timelineWithoutMarkup
}
export function timelineToSubtitles(timeline: Timeline, subtitlesConfig?: SubtitlesConfig) {
// Prepare subtitle configuration
timeline = deepClone(timeline)
let config = subtitlesConfig || {}
if (config.format && config.format == 'webvtt') {
config = { ...defaultSubtitlesBaseConfig, ...webVttConfigExtension, ...config }
} else {
config = { ...defaultSubtitlesBaseConfig, ...srtConfigExtension, ...config }
}
// Initialize subtitle file content
const lineBreakString = config.lineBreakString
let outText = ''
if (config.format == 'webvtt') {
outText += `WEBVTT${lineBreakString}Kind: captions${lineBreakString}`
if (config.language) {
outText += `Language: ${config.language}${lineBreakString}`
}
outText += lineBreakString
}
// Generate the cues from the given timeline
let cues: Cue[]
if (config.mode == 'segment' || config.mode == 'sentence') {
cues = getCuesFromTimeline_IsolateSegmentSentence(timeline, config)
} else if (config.mode == 'word' || config.mode == 'phone' || config.mode == 'word+phone') {
cues = getCuesFromTimeline_IsolateWordPhone(timeline, config)
} else if (config.mode == 'line') {
cues = getCuesFromTimeline_IsolateLines(timeline, config)
} else {
throw new Error('Invalid subtitles mode.')
}
// Extend cue end times with maximum added duration, if possible
if (cues.length > 0 &&
config.maxAddedDuration! > 0 &&
(config.mode === 'segment' || config.mode === 'sentence' || config.mode === 'line')) {
for (let i = 1; i < cues.length; i++) {
const currentCue = cues[i]
const previousCue = cues[i - 1]
previousCue.endTime = Math.min(previousCue.endTime + config.maxAddedDuration!, currentCue.startTime)
}
if (config.totalDuration != null) {
const lastCue = cues[cues.length - 1]
lastCue.endTime = Math.min(lastCue.endTime + config.maxAddedDuration!, config.totalDuration)
}
}
// Write cues to output text
for (let cueIndex = 0; cueIndex < cues.length; cueIndex++) {
outText += cueObjectToText(cues[cueIndex], cueIndex + 1, config)
}
return outText
}
// Generates subtitle cues from timeline. Ensures each segment or sentence starts in a new cue.
function getCuesFromTimeline_IsolateSegmentSentence(timeline: Timeline, config: SubtitlesConfig) {
if (timeline.length == 0) {
return []
}
// If the given timeline is a word timeline, wrap it with a segment and call again
if (timeline[0].type == 'word') {
const wordTimeline = timeline.filter(entry => isWordOrSymbolWord(entry.text))
const text = wordTimeline.map(entry => entry.text).join(' ')
const segmentEntry: TimelineEntry = {
type: 'segment',
text: text,
startTime: wordTimeline[0].startTime,
endTime: wordTimeline[wordTimeline.length - 1].endTime,
timeline: wordTimeline
}
return getCuesFromTimeline_IsolateSegmentSentence([segmentEntry], config)
}
const cues: Cue[] = []
// Generate one or more cues from each segment or sentence in the timeline.
for (let entry of timeline) {
if (entry.type == 'segment' && entry.timeline?.[0].type == 'sentence') {
if (config.mode == 'segment') {
// If the mode is 'segment', flatten all sentences to a single word timeline
entry.timeline = entry.timeline!.flatMap(t => t.timeline!)
} else {
cues.push(...getCuesFromTimeline_IsolateSegmentSentence(entry.timeline!, config))
continue
}
}
const entryText = entry.text
const maxLineWidth = config.maxLineWidth!
if (entryText.length <= maxLineWidth) {
cues.push({
lines: [entryText],
startTime: entry.startTime,
endTime: entry.endTime
})
continue
}
if (!entry.timeline || entry.timeline?.[0]?.type != 'word') {
continue
}
const wordTimeline = entry.timeline!.filter(entry => isWordOrSymbolWord(entry.text))
// First, add word start and end offsets for all word entries
let lastWordEndOffset = 0
for (const wordEntry of wordTimeline) {
const wordStartOffset = entryText.indexOf(wordEntry.text, lastWordEndOffset)
if (wordStartOffset == -1) {
throw new Error(`Couldn't find word '${wordEntry.text}' in its parent entry text`)
}
let wordEndOffset = wordStartOffset + wordEntry.text.length
lastWordEndOffset = wordEndOffset
wordEntry.startOffsetUtf16 = wordStartOffset
wordEntry.endOffsetUtf16 = wordEndOffset
}
// Add cues
let currentCue: Cue = {
lines: [],
startTime: -1,
endTime: -1
}
let lineStartWordOffset = 0
let lineStartOffset = 0
for (let wordIndex = 0; wordIndex < wordTimeline.length; wordIndex++) {
const isLastWord = wordIndex == wordTimeline.length - 1
const wordEntry = wordTimeline[wordIndex]
const wordEndOffset = wordEntry.endOffsetUtf16!
function getExtendedEndOffset(offset: number | undefined) {
if (offset == undefined) {
return entryText.length
}
while (charactersToWriteAhead.includes(entryText[offset])) {
offset += 1
}
return offset
}
const wordExtendedEndOffset = getExtendedEndOffset(wordEndOffset)
const nextWordEntry = wordTimeline[wordIndex + 1]
const nextWordExtendedEndOffset = getExtendedEndOffset(nextWordEntry?.endOffsetUtf16)
// Decide if to add to a new line
const lineLength = wordExtendedEndOffset - lineStartOffset
const lineLengthWithNextWord = nextWordExtendedEndOffset - lineStartOffset
const wordsRemaining = wordTimeline.length - wordIndex - 1
const phraseSeparators = [',', ',', '、', ';', ':', '),', '",', '”,', '.', '".', '”.', '."', '.”', '。']
const lineLengthWithNextWordExceedsMaxLineWidth = lineLengthWithNextWord >= maxLineWidth
const lineLengthExceedsHalfMaxLineWidth = lineLength >= maxLineWidth / 2
const wordsRemainingAreEqualOrLessToMinimumWordsInLine = wordsRemaining <= config.minWordsInLine!
const remainingTextExceedsMaxLineWidth = entryText.length - lineStartOffset > maxLineWidth
const followingSubstringIsPhraseSeparator = startsWithAnyOf(entryText.substring(wordEndOffset), phraseSeparators)
const shouldAddNewLine =
isLastWord ||
lineLengthWithNextWordExceedsMaxLineWidth ||
(remainingTextExceedsMaxLineWidth &&
lineLengthExceedsHalfMaxLineWidth &&
(wordsRemainingAreEqualOrLessToMinimumWordsInLine || (config.separatePhrases && followingSubstringIsPhraseSeparator)))
// If it was decided to add a new line
if (shouldAddNewLine) {
// Extend line end offset to end of sentence entry if last word encountered
let lineEndOffset: number
if (isLastWord) {
lineEndOffset = entryText.length
} else {
lineEndOffset = wordExtendedEndOffset
}
// Get line text
const lineText = entryText.substring(lineStartOffset, lineEndOffset)
// Find start and end times of line
const nextWordStartTime = isLastWord ? entry.endTime : wordTimeline[wordIndex + 1].startTime
const lineStartTime = wordTimeline[lineStartWordOffset].startTime
const lineEndTime = nextWordStartTime
// Add new line to cue
currentCue.lines.push(lineText)
// Update cue start and end times
if (currentCue.startTime == -1) {
currentCue.startTime = lineStartTime
}
currentCue.endTime = lineEndTime
// Finalize cue if needed
if (isLastWord || currentCue.lines.length == config.maxLineCount) {
cues.push(currentCue)
currentCue = {
lines: [],
startTime: -1,
endTime: -1
}
}
// Update offsets
lineStartOffset = lineEndOffset
lineStartWordOffset = wordIndex + 1
}
}
}
return cues
}
// Generates cues from timeline. Isolates words or phones in individual cues.
function getCuesFromTimeline_IsolateWordPhone(timeline: Timeline, config: SubtitlesConfig) {
if (timeline.length == 0) {
return []
}
const mode = config.mode!
const cues: Cue[] = []
for (const entry of timeline) {
const entryIsWord = entry.type == 'word'
const entryIsPhone = entry.type == 'phone'
const shouldIncludeEntry =
(entryIsWord && (mode == 'word' || mode == 'word+phone')) ||
(entryIsPhone && (mode == 'phone' || mode == 'word+phone'))
if (shouldIncludeEntry) {
cues.push({
lines: [entry.text],
startTime: entry.startTime,
endTime: entry.endTime,
})
}
if (entry.timeline) {
cues.push(...getCuesFromTimeline_IsolateWordPhone(entry.timeline, config))
}
}
return cues
}
// Generates cues from timeline. Isolates lines in individual cues.
function getCuesFromTimeline_IsolateLines(timeline: Timeline, config: SubtitlesConfig) {
if (timeline.length == 0) {
return []
}
const originalText = config.originalText
if (originalText == null) {
throw new Error(`'line' subtitles mode requires passing the original text in the 'originalText' property of the configuration object.`)
}
const lines = originalText.split(/(\r?\n)/g)
const charOffsetToLineNumber: number[] = []
for (let lineNumber = 0; lineNumber < lines.length; lineNumber++) {
const line = lines[lineNumber]
for (let i = 0; i < line.length; i++) {
charOffsetToLineNumber.push(lineNumber)
}
}
const cues: Cue[] = []
let currentCueWords: Timeline = []
function addCueFromCurrentWords() {
if (currentCueWords.length == 0) {
return
}
const firstWordEntry = currentCueWords[0]
const lastWordEntry = currentCueWords[currentCueWords.length - 1]
const lineNumber = charOffsetToLineNumber[firstWordEntry.startOffsetUtf16!]
const line = lines[lineNumber].trim()
cues.push({
lines: [line],
startTime: firstWordEntry.startTime,
endTime: lastWordEntry.endTime
})
currentCueWords = []
}
function addCuesFrom(timeline: Timeline) {
for (const entry of timeline) {
if (entry.type == 'word') {
const currentWordLineNumber = charOffsetToLineNumber[entry.startOffsetUtf16!]
const previousWordEntry = currentCueWords[currentCueWords.length - 1]
if (previousWordEntry) {
const previousWordLineNumber = charOffsetToLineNumber[previousWordEntry.startOffsetUtf16!]
if (currentWordLineNumber > previousWordLineNumber) {
addCueFromCurrentWords()
}
}
currentCueWords.push(entry)
} else if (entry.timeline) {
addCuesFrom(entry.timeline)
}
}
}
addCuesFrom(timeline)
addCueFromCurrentWords() // Add any remaining words
return cues
}
export function tryParseTimeRangePatternWithHours(line: string) {
const timeRangePatternWithHours = /^(\d+)\:(\d+)\:(\d+)[\.,](\d+)[ ]*-->[ ]*(\d+)\:(\d+)\:(\d+)[\.,](\d+)/
const match = timeRangePatternWithHours.exec(line)
if (!match) {
return { startTime: -1, endTime: -1, succeeded: false }
}
const startHours = parseInt(match[1])
const startMinutes = parseInt(match[2])
const startSeconds = parseInt(match[3])
const startMilliseconds = parseInt(match[4])
const endHours = parseInt(match[5])
const endMinutes = parseInt(match[6])
const endSeconds = parseInt(match[7])
const endMilliseconds = parseInt(match[8])
const startTime = (startMilliseconds / 1000) + (startSeconds) + (startMinutes * 60) + (startHours * 60 * 60)
const endTime = (endMilliseconds / 1000) + (endSeconds) + (endMinutes * 60) + (endHours * 60 * 60)
return { startTime, endTime, succeeded: true }
}
export function tryParseTimeRangePatternWithoutHours(line: string) {
const timeRangePatternWithHours = /^(\d+)\:(\d+)[\.,](\d+)[ ]*-->[ ]*(\d+)\:(\d+)[\.,](\d+)/
const match = timeRangePatternWithHours.exec(line)
if (!match) {
return { startTime: -1, endTime: -1, succeeded: false }
}
const startMinutes = parseInt(match[1])
const startSeconds = parseInt(match[2])
const startMilliseconds = parseInt(match[3])
const endMinutes = parseInt(match[4])
const endSeconds = parseInt(match[5])
const endMilliseconds = parseInt(match[6])
const startTime = (startMilliseconds / 1000) + (startSeconds) + (startMinutes * 60)
const endTime = (endMilliseconds / 1000) + (endSeconds) + (endMinutes * 60)
return { startTime, endTime, succeeded: true }
}
function cueObjectToText(cue: Cue, cueIndex: number, config: SubtitlesConfig) {
if (!cue || !cue.lines || cue.lines.length == 0) {
throw new Error(`Cue is empty`)
}
const lineBreakString = config.lineBreakString
let outText = ''
if (config.includeCueIndexes) {
outText += `${cueIndex}${lineBreakString}`
}
let formattedStartTime: string
let formattedEndTime: string
if (config.includeHours == true) {
formattedStartTime = formatHMS(secondsToHMS(cue.startTime), config.decimalSeparator)
formattedEndTime = formatHMS(secondsToHMS(cue.endTime), config.decimalSeparator)
} else {
formattedStartTime = formatMS(secondsToMS(cue.startTime), config.decimalSeparator)
formattedEndTime = formatMS(secondsToMS(cue.endTime), config.decimalSeparator)
}
outText += `${formattedStartTime} --> ${formattedEndTime}`
outText += `${lineBreakString}`
outText += cue.lines.map(line => line.trim()).join(lineBreakString)
outText += `${lineBreakString}`
outText += `${lineBreakString}`
return outText
}
export type Cue = {
lines: string[]
startTime: number
endTime: number
}
export type SubtitlesMode = 'line' | 'segment' | 'sentence' | 'word' | 'phone' | 'word+phone'
export interface SubtitlesConfig {
format?: 'srt' | 'webvtt'
language?: string
mode?: SubtitlesMode
maxLineCount?: number
maxLineWidth?: number
minWordsInLine?: number
separatePhrases?: boolean
maxAddedDuration?: number
decimalSeparator?: ',' | '.'
includeCueIndexes?: boolean
includeHours?: boolean
lineBreakString?: '\n' | '\r\n'
originalText?: string
totalDuration?: number
}
export const defaultSubtitlesBaseConfig: SubtitlesConfig = {
format: 'srt',
mode: 'sentence',
maxLineCount: 2,
maxLineWidth: 42,
minWordsInLine: 4,
separatePhrases: true,
maxAddedDuration: 3.0,
}
export const srtConfigExtension: SubtitlesConfig = {
decimalSeparator: ',',
includeCueIndexes: true,
includeHours: true,
lineBreakString: '\n',
}
export const webVttConfigExtension: SubtitlesConfig = {
decimalSeparator: '.',
includeCueIndexes: false,
includeHours: true,
lineBreakString: '\n',
}