-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutube-chapter-extractor.ts
executable file
·46 lines (37 loc) · 1.58 KB
/
youtube-chapter-extractor.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
#!/usr/bin/env -S deno run --allow-read --allow-write
/**
* Creates a simple mkvmerge chapter format file from timing/chapters extracted from text in inputFile
*/
export class ChapterFile {
public readonly content: string;
public readonly fileName: string;
private readonly linesToMatch = /(?<time>\d{2}:\d{2}:\d{2}|\d{2}:\d{2})\)?\s(\-)?(\s)?(?<chapterTitle>.*)/g;
constructor(inputFileName: string, inputFile: string) {
if (!this.linesToMatch.test(inputFile)) {
throw new Error("No chapter information found");
}
this.linesToMatch.lastIndex = 0; // reset the index after .test moved it on
this.fileName = `${inputFileName}_chapters.txt`;
const matchedLines = inputFile.matchAll(this.linesToMatch);
this.content = Array.from(matchedLines, (line, index) => {
const { time, chapterTitle } = line.groups!;
let chapterNumber: string;
if (index < 10) {
chapterNumber = `0${index}`;
} else chapterNumber = `${index}`;
return `CHAPTER${chapterNumber}=${
time.length === 5 ? `00:${time}` : time
}.000\nCHAPTER${chapterNumber}NAME=${chapterTitle}`;
}).join("\n");
}
}
if (import.meta.main) {
if (Deno.args.length !== 1) {
throw "Please supply one file name argument containing the text file to extract chapters from";
}
const inputFilename = Deno.args[0];
const inputFile = Deno.readTextFileSync(inputFilename);
const chapterFile = new ChapterFile(inputFilename, inputFile);
Deno.writeTextFile(chapterFile.fileName, chapterFile.content);
console.log(`${chapterFile.fileName} file has been generated`);
}