File size: 10,298 Bytes
8dd5bba
 
 
8ba367b
8dd5bba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3807db1
8dd5bba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3807db1
8dd5bba
 
217d1ce
 
 
8dd5bba
 
217d1ce
 
 
 
 
8dd5bba
 
 
 
 
 
 
 
 
3807db1
 
 
 
 
 
 
 
 
8dd5bba
 
 
 
 
 
 
 
 
 
 
217d1ce
 
 
 
 
 
 
 
 
 
 
 
 
8dd5bba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a87eec
 
 
 
8dd5bba
6a87eec
8dd5bba
 
 
6a87eec
8dd5bba
 
 
 
 
217d1ce
8dd5bba
 
 
 
 
 
 
 
6a87eec
 
8dd5bba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ba367b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217d1ce
 
 
 
 
 
 
 
 
 
 
8ba367b
 
 
 
 
 
 
 
 
 
217d1ce
 
8ba367b
 
 
 
 
 
217d1ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { fileURLToPath } from 'url';
import { readFileSync, createWriteStream, existsSync } from 'fs';
import { Plugin } from './plugin.js';
import path from 'path';
import fs from 'fs';

export class CaptionPlugin extends Plugin {
  constructor(name, options) {
    super(name, options);
  }
  async applyPrerender(originalManuscript, jobId) {
    let transcript = originalManuscript.transcript
    for (let item of transcript) {
      let audioCaptionFileFileName = path.basename(item.audioCaptionFile)
      if (path.extname(audioCaptionFileFileName) == '.ass') {
        continue
      }
      let originalCaption = path.join(process.cwd(), item.audioCaptionFile)
      if (!fs.existsSync(originalCaption)) {
        originalCaption = path.join(process.cwd(), 'public', audioCaptionFileFileName)
      }
      if (!originalCaption) continue;
      let outputCaptionFile = originalCaption.replace('.json', '.ass')
      await this.generateCaptions(
        {
          ...this.options,
          captionFilePath: originalCaption,
          outputFilePath: outputCaptionFile,
        }
      )
      item._audioCaptionFile = item.audioCaptionFile
      item.audioCaptionFile = item.audioCaptionFile.replace('.json', '.ass')
    }
  }
  async applyPostrender(originalManuscript, jobId, outFiles) {
  }



  /**

   * Generate ASS subtitle file with word highlighting

   * @param {Object} options

   * @param {string} options.captionFilePath - Path to input JSON caption file

   * @param {string} options.outputFilePath - Path to output ASS file

   * @param {string} options.capitalize - capitalize the font. upper, full-upper, small, none

   * @param {number} [options.tiltDegrees=8] - Tilt angle in degrees (alternates between +/-)

   * @param {number} [options.translateY=200] - Distance from bottom in pixels

   * @param {number} [options.widthPercent=80] - Width percentage for text centering (0-100)

   * @param {string} [options.fontName='Impact'] - Font name

   * @param {number} [options.fontSize=72] - Font size

   * @param {number} [options.wordsPerGroup=4] - Number of words per caption group

   * @param {number} [options.videoWidth=1920] - Video width for positioning

   * @param {number} [options.videoHeight=1080] - Video height for positioning

   * @returns {Promise<string>} Path to generated ASS file

   */
  async generateCaptions(options) {
    const {
      captionFilePath,
      outputFilePath,
      tiltDegrees = 8,
      translateY = 200,
      widthPercent = 80,
      fontName = 'Impact',
      fontSize = 72,
      capitalize = 'upper',
      wordsPerGroup = 4,
      videoWidth = 1920,
      videoHeight = 1080,
      fontColor = '#FFFFFF',
      fontHighlightColor = '#00FF00'
    } = options;

    const assFontColor = hexToASSColor(fontColor);
    const assHighlightColor = hexToASSColor(fontHighlightColor);
    const assHighlightColorInline = `${assHighlightColor}&`;
    const assFontColorInline = `${assFontColor}&`;

    // Read and parse JSON file
    const jsonData = JSON.parse(readFileSync(captionFilePath, 'utf-8'));
    const transcript = jsonData.transcript || '';
    let words = jsonData.words || [];

    if (words.length === 0) {
      throw new Error('No words found in caption file');
    }

    if (capitalize == 'full-upper') {
      words = words.map(w => ({ ...w, word: w.word.toUpperCase() }));
    }
    else if (capitalize == 'upper') {
      words = words.map(w => ({ ...w, word: w.word.charAt(0).toUpperCase() + w.word.slice(1) }));
    }
    else if (capitalize == 'small') {
      words = words.map(w => ({ ...w, word: w.word.toLowerCase() }));
    }
    // Assign sentence indices to words
    words = assignSentenceToWords(words, transcript);

    // Calculate margins for centering within width percentage
    const totalMargin = videoWidth * (1 - widthPercent / 100);
    const sideMargin = Math.floor(totalMargin / 2);

    // Create output stream
    const output = createWriteStream(outputFilePath);

    // Write header with calculated margins
    output.write(
      createASSHeader(
        videoWidth,
        videoHeight,
        fontName,
        fontSize,
        translateY,
        sideMargin,
        sideMargin,
        assFontColor,
        assHighlightColor
      )
    );

    // Process words in groups respecting sentence boundaries
    let i = 0;
    let groupIdx = 0;

    while (i < words.length) {
      const currentSentence = words[i].sentence_idx || 0;

      // Collect words for this group (up to wordsPerGroup, same sentence only)
      const wordGroup = [];
      let j = i;

      while (j < words.length && wordGroup.length < wordsPerGroup) {
        if ((words[j].sentence_idx || 0) === currentSentence) {
          wordGroup.push(words[j]);
          j++;
        } else {
          break; // Stop at sentence boundary
        }
      }

      if (wordGroup.length === 0) {
        i++;
        continue;
      }

      // Alternate tilt
      const currentTilt = groupIdx % 2 === 0 ? tiltDegrees : -tiltDegrees;
      const tiltTag = `{\\frz${currentTilt}}`;

      // Calculate positioning for centering
      const posTag = sideMargin > 0 ? `{\\an2\\pos(${videoWidth / 2},${videoHeight - translateY})}` : '';

      // Get the full group duration (from first word start to last word end)
      const groupStart = wordGroup[0].start;
      const groupEnd = wordGroup[wordGroup.length - 1].end;

      // For each word in the group, create an event with highlighting
      // Use the FULL GROUP duration for each event to ensure no gaps
      for (let wordIdx = 0; wordIdx < wordGroup.length; wordIdx++) {
        const wordObj = wordGroup[wordIdx];
        const wordStart = wordObj.start;
        const wordEnd = wordIdx < wordGroup.length - 1 ? wordGroup[wordIdx + 1].start : wordObj.end;

        // Build the caption text with highlighting
        const captionParts = wordGroup.map((w, idx) => {
          if (idx === wordIdx) {
            // Current word - highlighted in green
            return `{\\c${assHighlightColorInline}}${w.word}{\\c${assFontColorInline}}`;
          } else {
            // Other words - white
            return w.word;
          }
        });

        const captionText = tiltTag + posTag + captionParts.join(' ');

        // Write dialogue line with timing from current word start to next word start (or group end)
        // This ensures continuous display with no gaps between words
        output.write(`Dialogue: 0,${formatTimestampASS(wordStart)},${formatTimestampASS(wordEnd)},Default,,0,0,0,,${captionText}\n`);
      }

      i = j;
      groupIdx++;
    }

    output.end();

    return new Promise((resolve, reject) => {
      output.on('finish', () => {
        this.log(`Generated ${path.basename(outputFilePath)} captions`);
        resolve(outputFilePath);
      });
      output.on('error', reject);
    });
  }
}


/**

 * Format seconds to ASS timestamp format (H:MM:SS.cc)

 * @param {number} seconds 

 * @returns {string}

 */
function formatTimestampASS(seconds) {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toFixed(2).padStart(5, '0')}`;
}

/**

 * Split transcript into sentences

 * @param {string} transcript 

 * @returns {string[]}

 */
function splitIntoSentences(transcript) {
  const parts = transcript.split(/([.!?]+)\s+/);
  const result = [];

  for (let i = 0; i < parts.length - 1; i += 2) {
    if (i + 1 < parts.length) {
      result.push(parts[i] + parts[i + 1]);
    } else {
      result.push(parts[i]);
    }
  }

  if (parts.length % 2 === 1) {
    result.push(parts[parts.length - 1]);
  }

  return result;
}

/**

 * Assign sentence index to each word

 * @param {Array} words 

 * @param {string} transcript 

 * @returns {Array}

 */
function assignSentenceToWords(words, transcript) {
  const sentences = splitIntoSentences(transcript);

  let wordIdx = 0;
  sentences.forEach((sentence, sentIdx) => {
    const sentenceWords = sentence.split(/\s+/);
    sentenceWords.forEach(() => {
      if (wordIdx < words.length) {
        words[wordIdx].sentence_idx = sentIdx;
        wordIdx++;
      }
    });
  });

  return words;
}

/**

 * Create ASS file header with styles

 * @param {number} videoWidth 

 * @param {number} videoHeight 

 * @param {string} fontName 

 * @param {number} fontSize 

 * @param {number} marginV 

 * @returns {string}

 */
function createASSHeader(

  videoWidth = 1920,

  videoHeight = 1080,

  fontName = 'Impact',

  fontSize = 72,

  marginV = 200,

  marginL = 10,

  marginR = 10,

  primaryColor = '&H00FFFFFF',

  highlightColor = '&H0000FF00'

) {
  return `[Script Info]

Title: Word-by-Word Captions

ScriptType: v4.00+

WrapStyle: 0

PlayResX: ${videoWidth}

PlayResY: ${videoHeight}

ScaledBorderAndShadow: yes



[V4+ Styles]

Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding

Style: Default,${fontName},${fontSize},${primaryColor},&H000000FF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,3,2,2,${marginL},${marginR},${marginV},1

Style: Highlight,${fontName},${fontSize},${highlightColor},&H000000FF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,3,2,2,${marginL},${marginR},${marginV},1



[Events]

Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text

`;
}

function hexToASSColor(hexValue) {
  if (typeof hexValue !== 'string') {
    throw new Error('fontColor values must be hex strings like #RRGGBB');
  }

  const normalized = hexValue.trim().replace('#', '');
  if (!/^[0-9a-fA-F]{6}$/.test(normalized)) {
    throw new Error(`Invalid hex color provided: ${hexValue}`);
  }

  const r = normalized.slice(0, 2);
  const g = normalized.slice(2, 4);
  const b = normalized.slice(4, 6);
  return `&H00${b}${g}${r}`.toUpperCase();
}