-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateClips.js
More file actions
831 lines (733 loc) · 24.8 KB
/
createClips.js
File metadata and controls
831 lines (733 loc) · 24.8 KB
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
#!/usr/bin/env node
import { config as loadEnv } from 'dotenv';
import fs from 'fs/promises';
import fsSync from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import YTDlpWrapModule from 'yt-dlp-wrap';
import ffmpeg from 'fluent-ffmpeg';
import OpenAI from 'openai';
loadEnv();
const REQUIRED_ENV = ['OPENAI_API_KEY'];
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const TEMP_DIR = path.join(__dirname, 'temp');
const CLIPS_DIR = path.join(__dirname, 'clips');
const VIDEO_FILE = path.join(TEMP_DIR, 'source_video.mp4');
const CAPTIONS_BASENAME = path.join(TEMP_DIR, 'captions');
const CAPTIONS_GLOB = /\.json3$/;
const TARGET_WIDTH = 1080;
const TARGET_HEIGHT = 1920;
const GPT_FULL_ANALYSIS_TOKEN_LIMIT = 220000;
const CHUNK_WORD_LIMIT = 4000;
const MAX_CHUNK_CLIPS = 3;
const MAX_FINAL_CANDIDATES = 18;
const EXCERPT_WORD_MARGIN = 20;
const EXCERPT_CHAR_LIMIT = 420;
const YTDlpWrap = YTDlpWrapModule?.default ?? YTDlpWrapModule;
const ytDlp = new YTDlpWrap();
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
function normalizeYoutubeUrl(input) {
const trimmed = (input ?? '').trim();
if (!trimmed) {
throw new Error('A YouTube URL is required.');
}
const cleaned = trimmed.replace(/\\(?=[/?&=])/g, '');
let parsed;
try {
parsed = new URL(cleaned);
} catch (error) {
throw new Error(`Invalid URL provided: ${input}`);
}
if (!['http:', 'https:'].includes(parsed.protocol)) {
throw new Error(`Unsupported URL protocol: ${parsed.protocol}`);
}
const hostname = parsed.hostname.toLowerCase();
const isYoutube =
hostname === 'youtu.be' ||
hostname.endsWith('.youtube.com') ||
hostname === 'youtube.com';
if (!isYoutube) {
throw new Error('The URL must point to YouTube.');
}
return parsed.href;
}
async function ensureEnvironment() {
const missing = REQUIRED_ENV.filter((key) => !process.env[key]);
if (missing.length) {
throw new Error(
`Missing required environment variables: ${missing.join(', ')}. ` +
'Create an .env file with these keys or export them before running the script.'
);
}
}
async function ensureDirectories() {
await fs.mkdir(TEMP_DIR, { recursive: true });
await fs.mkdir(CLIPS_DIR, { recursive: true });
}
async function fetchCaptionsTranscript(url) {
console.log('→ Fetching YouTube captions...');
const existingEntries = await fs.readdir(TEMP_DIR).catch(() => []);
await Promise.all(
existingEntries
.filter((entry) => CAPTIONS_GLOB.test(entry))
.map((entry) => fs.rm(path.join(TEMP_DIR, entry), { force: true }).catch(() => {}))
);
await ytDlp.execPromise([
url,
'--skip-download',
'--write-auto-sub',
'--write-sub',
'--sub-lang',
'en',
'--sub-format',
'json3',
'-o',
CAPTIONS_BASENAME
]);
const entries = await fs.readdir(TEMP_DIR);
const captionFile = entries.find((entry) => CAPTIONS_GLOB.test(entry));
if (!captionFile) {
throw new Error(
'Failed to download captions. This video may not have subtitles in the requested language.'
);
}
const raw = await fs.readFile(path.join(TEMP_DIR, captionFile), 'utf8');
let json;
try {
json = JSON.parse(raw);
} catch (error) {
throw new Error(`Unable to parse captions JSON: ${error.message}`);
}
return convertCaptionsToTranscript(json);
}
function convertCaptionsToTranscript(captionsJson) {
const events = Array.isArray(captionsJson?.events) ? captionsJson.events : [];
if (!events.length) {
throw new Error('Captions JSON does not contain any timed events.');
}
const segments = [];
const words = [];
const transcriptPieces = [];
events.forEach((event, index) => {
const startMs =
typeof event.tStartMs === 'number'
? event.tStartMs
: typeof event.ts === 'number'
? event.ts
: 0;
const nextStartMs =
typeof events[index + 1]?.tStartMs === 'number'
? events[index + 1].tStartMs
: startMs + 2000;
const durationMsOptions = [
event.dDurationMs,
event.mDurationMs,
event.tDurMs,
event.dur,
event.durationMs
].filter((value) => typeof value === 'number' && value > 0);
const durationMs =
durationMsOptions.length > 0 ? durationMsOptions[0] : Math.max(nextStartMs - startMs, 1500);
const start = startMs / 1000;
const end = (startMs + durationMs) / 1000;
const segs = Array.isArray(event.segs) ? event.segs : [];
const text = segs
.map((seg) => (typeof seg.utf8 === 'string' ? seg.utf8 : ''))
.join('')
.replace(/\n/g, ' ')
.replace(/\u2028/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!text) {
return;
}
transcriptPieces.push(text);
const segmentWords = [];
const tokens = text.split(/\s+/).filter(Boolean);
if (tokens.length) {
const durationSeconds = Math.max(end - start, tokens.length * 0.35);
const perWord = durationSeconds / tokens.length;
tokens.forEach((token, wordIndex) => {
const wordStart = start + perWord * wordIndex;
const wordEnd = wordStart + perWord;
const wordEntry = {
start: Number(wordStart.toFixed(3)),
end: Number(wordEnd.toFixed(3)),
word: token
};
segmentWords.push(wordEntry);
words.push(wordEntry);
});
}
segments.push({
start,
end,
text,
words: segmentWords
});
});
return {
text: transcriptPieces.join(' ').replace(/\s+/g, ' ').trim(),
segments,
words: words.sort((a, b) => (a.start ?? 0) - (b.start ?? 0))
};
}
async function downloadVideo(url) {
if (fsSync.existsSync(VIDEO_FILE)) {
return VIDEO_FILE;
}
console.log('→ Downloading full-quality video...');
await ytDlp.execPromise([
url,
'-f',
'bv*+ba/b',
'--merge-output-format',
'mp4',
'-o',
path.join(TEMP_DIR, 'source_video.%(ext)s')
]);
if (!fsSync.existsSync(VIDEO_FILE)) {
throw new Error('Video download did not produce the expected MP4 file.');
}
return VIDEO_FILE;
}
async function analyseTranscript(transcript) {
console.log('→ Analysing transcript with GPT-5...');
const transcriptJson = JSON.stringify(transcript);
if (estimateTokenCount(transcriptJson) <= GPT_FULL_ANALYSIS_TOKEN_LIMIT) {
return runSinglePassAnalysis(transcript);
}
return runChunkedTranscriptAnalysis(transcript);
}
async function runSinglePassAnalysis(transcript) {
const prompt = [
{
role: 'system',
content:
'You are an expert viral video producer. Your task is to analyse the provided video transcript and identify the 3 to 5 most engaging, high-impact segments that would perform well as short-form social media clips. A great clip is self-contained, has a strong hook, and delivers a key piece of information or emotion.\n\nThe transcript is provided as a JSON object with word-level timestamps in seconds.\n\nPlease return your answer ONLY as a valid JSON array of objects. Each object in the array should represent a clip and have the following structure: {"title": "A short, catchy title for the clip", "start_time": 65.5, "end_time": 92.0, "reason": "A brief explanation of why this segment is compelling."}'
},
{
role: 'user',
content: transcriptToJsonString(transcript)
}
];
const raw = await sendGptRequest(prompt);
const clips = parseClipArray(raw, 'full-transcript analysis');
validateClips(clips);
return clips.map(normalizeClip);
}
async function runChunkedTranscriptAnalysis(transcript) {
const chunks = chunkTranscript(transcript, CHUNK_WORD_LIMIT);
if (!chunks.length) {
throw new Error('Transcript did not contain enough caption data to analyse.');
}
console.log(`→ Transcript is large; analysing in ${chunks.length} chunks...`);
const candidates = [];
for (let index = 0; index < chunks.length; index += 1) {
const chunk = chunks[index];
console.log(
` ↳ Chunk ${index + 1}/${chunks.length} (start ${chunk.start.toFixed(
0
)}s, end ${chunk.end.toFixed(0)}s)`
);
try {
const chunkCandidates = await analyseTranscriptChunk(chunk, index, chunks.length);
candidates.push(...chunkCandidates);
} catch (error) {
console.warn(`⚠️ Skipped chunk ${index + 1}: ${error.message}`);
}
}
if (!candidates.length) {
throw new Error('Unable to derive candidate clips from the transcript chunks.');
}
const deduped = dedupeClips(candidates);
const limitedCandidates = deduped.slice(0, MAX_FINAL_CANDIDATES);
const finalClips = await selectFinalClipsFromCandidates(transcript, limitedCandidates);
if (finalClips.length >= 3 && finalClips.length <= 5) {
return finalClips.map(normalizeClip);
}
if (finalClips.length >= 3) {
return finalClips.slice(0, 5).map(normalizeClip);
}
const fallback = limitedCandidates.slice(0, 5).map(normalizeClip);
if (fallback.length < 3) {
throw new Error('Not enough viable clip candidates were generated.');
}
return fallback.slice(0, 5);
}
async function analyseTranscriptChunk(chunk, index, totalChunks) {
const prompt = [
{
role: 'system',
content:
`You are an expert viral video producer. Focus only on the provided transcript chunk (chunk ${index + 1} of ${totalChunks}). Identify up to ${MAX_CHUNK_CLIPS} compelling short-form clip ideas within this chunk. ` +
'Clips must use absolute timestamps in seconds relative to the full video. Return ONLY a JSON array (length 0 to ' +
`${MAX_CHUNK_CLIPS}) with objects of the form {"title": "...", "start_time": 0, "end_time": 0, "reason": "..."}.`
},
{
role: 'user',
content: JSON.stringify({
chunk_index: index + 1,
total_chunks: totalChunks,
start_time: chunk.start,
end_time: chunk.end,
transcript: chunk.transcript
})
}
];
const raw = await sendGptRequest(prompt);
const clips = parseClipArray(raw, `chunk ${index + 1}`);
const normalized = [];
clips
.slice(0, MAX_CHUNK_CLIPS)
.forEach((clip, clipIndex) => {
try {
const candidate = normalizeClip(clip);
if (
candidate.start_time < chunk.start - 5 ||
candidate.end_time > chunk.end + 5
) {
throw new Error('clip timestamps fall outside the current chunk window');
}
normalized.push({
...candidate,
source_chunk: index + 1
});
} catch (error) {
console.warn(
`⚠️ Ignoring clip ${clipIndex + 1} from chunk ${index + 1}: ${error.message}`
);
}
});
return normalized;
}
async function selectFinalClipsFromCandidates(transcript, candidates) {
if (!candidates.length) {
return [];
}
const enrichedCandidates = candidates.map((clip) => ({
...clip,
transcript_excerpt: buildTranscriptExcerpt(transcript, clip.start_time, clip.end_time)
}));
const prompt = [
{
role: 'system',
content:
'You are an expert viral video producer. From the provided shortlist of candidate clips, select the 3 to 5 options that will perform best as short-form social media videos. Balance emotional impact, clarity, and hook value, and avoid redundant or overlapping clips. Return ONLY a JSON array of the final clips with the same structure as provided.'
},
{
role: 'user',
content: JSON.stringify({
candidates: enrichedCandidates
})
}
];
const raw = await sendGptRequest(prompt);
const clips = parseClipArray(raw, 'final candidate selection');
validateClips(clips, { min: 0, max: 5 });
return clips.map(normalizeClip);
}
function transcriptToJsonString(transcript) {
return JSON.stringify(transcript);
}
function estimateTokenCount(text) {
if (!text) {
return 0;
}
return Math.ceil(text.length / 4);
}
async function sendGptRequest(messages) {
const completion = await openai.chat.completions.create({
model: 'gpt-5',
messages
});
const [{ message }] = completion.choices;
const rawContent = message?.content;
const raw =
Array.isArray(rawContent) && rawContent.length
? rawContent.map((part) => part.text ?? '').join('').trim()
: typeof rawContent === 'string'
? rawContent.trim()
: '';
if (!raw) {
throw new Error('GPT-5 returned an empty response.');
}
return raw;
}
function parseClipArray(raw, context) {
let parsed;
try {
parsed = JSON.parse(raw);
} catch (error) {
throw new Error(`Failed to parse ${context} response as JSON: ${error.message}`);
}
if (Array.isArray(parsed)) {
return parsed;
}
if (parsed && Array.isArray(parsed.clips)) {
return parsed.clips;
}
throw new Error(`${context} response was not a JSON array.`);
}
function validateClips(clips, { min = 3, max = 5 } = {}) {
if (!Array.isArray(clips)) {
throw new Error('Model response was not an array.');
}
if (typeof min === 'number' && clips.length < min) {
throw new Error(`Model returned fewer than ${min} clips.`);
}
if (typeof max === 'number' && clips.length > max) {
throw new Error(`Model returned more than ${max} clips.`);
}
clips.forEach((clip, index) => {
const start = Number(clip?.start_time ?? clip?.start ?? clip?.startTime);
const end = Number(clip?.end_time ?? clip?.end ?? clip?.endTime);
if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) {
throw new Error(`Invalid timestamps for clip at index ${index}.`);
}
});
}
function normalizeClip(rawClip) {
if (!rawClip) {
throw new Error('Clip data is missing.');
}
const title = typeof rawClip.title === 'string' ? rawClip.title.trim() : '';
const start = Number(rawClip.start_time ?? rawClip.start ?? rawClip.startTime);
const end = Number(rawClip.end_time ?? rawClip.end ?? rawClip.endTime);
if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) {
throw new Error('Clip timestamps must be valid numbers with end > start.');
}
const reason =
typeof rawClip.reason === 'string' && rawClip.reason.trim()
? rawClip.reason.trim()
: 'This segment provides a strong hook and a clear takeaway.';
const sourceChunk =
typeof rawClip.source_chunk === 'number' ? rawClip.source_chunk : undefined;
return {
title: title || `Clip_${Math.round(start)}`,
start_time: start,
end_time: end,
reason,
...(sourceChunk ? { source_chunk: sourceChunk } : {})
};
}
function chunkTranscript(transcript, maxWordsPerChunk) {
const allWords = extractWords(transcript)
.filter(
(word) =>
typeof word.start === 'number' &&
typeof word.end === 'number' &&
word.end > word.start
)
.sort((a, b) => (a.start ?? 0) - (b.start ?? 0));
if (!allWords.length) {
return [];
}
const segments = Array.isArray(transcript.segments) ? transcript.segments : [];
const chunks = [];
for (let index = 0; index < allWords.length; index += maxWordsPerChunk) {
const chunkWords = allWords
.slice(index, index + maxWordsPerChunk)
.map((word) => ({ ...word }));
const chunkStart = chunkWords[0].start ?? 0;
const chunkEnd = chunkWords[chunkWords.length - 1].end ?? chunkStart;
const chunkSegments = segments
.filter((segment) => {
const segStart = typeof segment.start === 'number' ? segment.start : chunkStart;
const segEnd = typeof segment.end === 'number' ? segment.end : segStart;
return segEnd >= chunkStart && segStart <= chunkEnd;
})
.map((segment) => ({
...segment,
words: Array.isArray(segment.words)
? segment.words
.filter((word) => {
const wStart = typeof word.start === 'number' ? word.start : chunkStart;
const wEnd = typeof word.end === 'number' ? word.end : wStart;
return wEnd >= chunkStart && wStart <= chunkEnd;
})
.map((word) => ({ ...word }))
: undefined
}));
const textSource =
chunkSegments.length > 0
? chunkSegments.map((segment) => segment.text ?? '').join(' ')
: chunkWords.map((word) => word.word ?? '').join(' ');
const chunkText = textSource.replace(/\s+/g, ' ').trim();
chunks.push({
start: chunkStart,
end: chunkEnd,
transcript: {
text: chunkText,
words: chunkWords,
segments: chunkSegments
}
});
}
return chunks;
}
function dedupeClips(clips) {
const seen = new Set();
const result = [];
clips.forEach((clip) => {
try {
const normalized = normalizeClip(clip);
const key = `${Math.round(normalized.start_time * 10)}-${Math.round(
normalized.end_time * 10
)}`;
if (seen.has(key)) {
return;
}
seen.add(key);
result.push({
...normalized,
reason: normalized.reason,
...(clip.source_chunk ? { source_chunk: clip.source_chunk } : {})
});
} catch (error) {
console.warn(`⚠️ Dropping candidate clip: ${error.message}`);
}
});
return result.sort((a, b) => a.start_time - b.start_time);
}
function buildTranscriptExcerpt(transcript, startTime, endTime) {
const words = extractWords(transcript).filter((word) => {
if (typeof word.start !== 'number' || typeof word.end !== 'number') {
return false;
}
return word.end >= startTime - 1 && word.start <= endTime + 1;
});
let excerpt = words.map((word) => word.word ?? '').join(' ').replace(/\s+/g, ' ').trim();
if (!excerpt && Array.isArray(transcript.segments)) {
excerpt = transcript.segments
.filter((segment) => {
const segStart = typeof segment.start === 'number' ? segment.start : startTime;
const segEnd = typeof segment.end === 'number' ? segment.end : segStart;
return segEnd >= startTime - 1 && segStart <= endTime + 1;
})
.map((segment) => segment.text ?? '')
.join(' ')
.replace(/\s+/g, ' ')
.trim();
}
if (!excerpt) {
return '';
}
const excerptWords = excerpt.split(/\s+/);
const limit = EXCERPT_WORD_MARGIN * 2;
const trimmedWords = excerptWords.slice(0, limit);
let trimmed = trimmedWords.join(' ');
if (excerptWords.length > trimmedWords.length) {
trimmed = `${trimmed}…`;
}
if (trimmed.length > EXCERPT_CHAR_LIMIT) {
trimmed = `${trimmed.slice(0, EXCERPT_CHAR_LIMIT).trim()}…`;
}
return trimmed;
}
function extractWords(transcript) {
if (Array.isArray(transcript.words)) {
return transcript.words;
}
if (Array.isArray(transcript.segments)) {
return transcript.segments.flatMap((segment) =>
Array.isArray(segment.words)
? segment.words
: [
{
start: segment.start,
end: segment.end,
word: segment.text?.trim() ?? ''
}
]
);
}
throw new Error('Transcript does not contain word-level timing information.');
}
function secondsToAssTime(seconds) {
const rounded = Math.max(seconds, 0);
const hours = Math.floor(rounded / 3600)
.toString()
.padStart(1, '0');
const minutes = Math.floor((rounded % 3600) / 60)
.toString()
.padStart(2, '0');
const secs = (rounded % 60).toFixed(2).padStart(5, '0');
return `${hours}:${minutes}:${secs}`;
}
function chunkWordsIntoEvents(words) {
const events = [];
let buffer = [];
let chunkStart = null;
words.forEach((word) => {
const cleanedWord = (word.word ?? '').replace(/\s+/g, ' ').trim();
if (!cleanedWord) {
return;
}
if (chunkStart === null) {
chunkStart = word.start ?? 0;
}
buffer.push(cleanedWord);
const lastChar = cleanedWord.slice(-1);
const durationExceeded = buffer.length >= 8;
const sentenceEnded = ['.', '!', '?'].includes(lastChar);
if (durationExceeded || sentenceEnded) {
events.push({
start: chunkStart,
end: (word.end ?? word.start ?? chunkStart) + 0.15,
text: buffer.join(' ').replace(/\s+/g, ' ').trim()
});
buffer = [];
chunkStart = null;
}
});
if (buffer.length) {
const lastWord = words[words.length - 1];
events.push({
start: chunkStart ?? lastWord.start ?? 0,
end: (lastWord.end ?? lastWord.start ?? 0) + 0.2,
text: buffer.join(' ').replace(/\s+/g, ' ').trim()
});
}
return events;
}
async function buildAssFile(transcript, clip, baseName) {
const words = extractWords(transcript).filter(
(word) =>
typeof word.start === 'number' &&
typeof word.end === 'number' &&
word.end >= clip.start_time &&
word.start <= clip.end_time
);
if (!words.length) {
throw new Error(`No transcript words fall inside the clip window "${clip.title}".`);
}
const events = chunkWordsIntoEvents(words);
const assEvents = events
.map((event) => {
const startOffset = event.start - clip.start_time;
const endOffset = event.end - clip.start_time;
const start = secondsToAssTime(Math.max(startOffset, 0));
const end = secondsToAssTime(Math.max(endOffset, startOffset + 0.5));
const text = event.text.replace(/([\\{}])/g, '\\$1');
return `Dialogue: 0,${start},${end},Default,,0,0,0,,{\\an5\\bord6\\shad0\\1c&HFFFFFF&\\3c&H000000&\\fs70\\b1}${text}`;
})
.join('\n');
const assContent = `[Script Info]
ScriptType: v4.00+
PlayResX: 1080
PlayResY: 1920
WrapStyle: 2
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,Montserrat,70,&H00FFFFFF,&H000000FF,&H00202020,&H64000000,1,0,0,0,100,100,0,0,1,6,0,5,60,60,80,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
${assEvents}
`;
const captionPath = path.join(TEMP_DIR, `${baseName}.ass`);
await fs.writeFile(captionPath, assContent, 'utf8');
return captionPath;
}
function sanitizeFileName(input) {
const fallback = `clip_${Date.now()}`;
if (typeof input !== 'string' || !input.trim()) {
return fallback;
}
const normalized = input
.normalize('NFKD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-zA-Z0-9-_]+/g, '_')
.replace(/_+/g, '_')
.replace(/^_+|_+$/g, '');
return normalized || fallback;
}
async function renderClip(videoPath, clip, captionsPath, baseName) {
const duration = clip.end_time - clip.start_time;
if (duration <= 0) {
throw new Error(`Clip "${clip.title}" has a non-positive duration.`);
}
const outputPath = path.join(CLIPS_DIR, `${baseName}.mp4`);
console.log(`→ Rendering clip "${clip.title}" (${duration.toFixed(2)}s)...`);
await new Promise((resolve, reject) => {
const assFilterPath = captionsPath.replace(/\\/g, '\\\\').replace(/:/g, '\\:');
const filterChain = [
`scale=${TARGET_WIDTH}:${TARGET_HEIGHT}:force_original_aspect_ratio=increase`,
`crop=${TARGET_WIDTH}:${TARGET_HEIGHT}`,
`ass=${assFilterPath}`
].join(',');
ffmpeg(videoPath)
.setStartTime(clip.start_time)
.setDuration(duration)
.videoFilters(filterChain)
.outputOptions([
'-c:v', 'libx264',
'-preset', 'veryfast',
'-crf', '18',
'-c:a', 'aac',
'-b:a', '192k',
'-movflags', '+faststart'
])
.save(outputPath)
.on('end', resolve)
.on('error', reject);
});
return outputPath;
}
async function cleanupTemp() {
try {
const entries = await fs.readdir(TEMP_DIR);
await Promise.all(
entries.map((entry) => fs.rm(path.join(TEMP_DIR, entry), { recursive: true, force: true }))
);
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}
}
async function main() {
const [, , rawUrl] = process.argv;
if (!rawUrl) {
console.error('Usage: node createClips.js "<youtube-url>"');
process.exit(1);
}
let url;
try {
url = normalizeYoutubeUrl(rawUrl);
} catch (error) {
console.error(`❌ ${error.message}`);
process.exit(1);
}
await ensureEnvironment();
await ensureDirectories();
try {
const transcript = await fetchCaptionsTranscript(url);
const clips = await analyseTranscript(transcript);
const videoPath = await downloadVideo(url);
const seenNames = new Map();
for (const clip of clips) {
const safeBase = sanitizeFileName(clip.title);
const index = seenNames.get(safeBase) ?? 0;
seenNames.set(safeBase, index + 1);
const baseName = index ? `${safeBase}_${index + 1}` : safeBase;
const captionsPath = await buildAssFile(transcript, clip, baseName);
await renderClip(videoPath, clip, captionsPath, baseName);
}
console.log(`✅ Finished! Clips saved to ${CLIPS_DIR}`);
} catch (error) {
console.error(`❌ ${error.message}`);
process.exitCode = 1;
} finally {
try {
await cleanupTemp();
} catch (cleanupError) {
console.warn(`⚠️ Failed to fully clean temp directory: ${cleanupError.message}`);
}
}
}
main();