Skip to content

Instantly share code, notes, and snippets.

@arnaudrenaud
Last active April 24, 2024 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnaudrenaud/39444639b4183727492a18514baea916 to your computer and use it in GitHub Desktop.
Save arnaudrenaud/39444639b4183727492a18514baea916 to your computer and use it in GitHub Desktop.
Generate subtitles SRT file from raw text file
const { readFileSync, writeFileSync } = require("fs");
function getFormattedTime(timeMilliseconds) {
return new Date(timeMilliseconds).toISOString().substring(11, 23);
}
const REPLACEMENT_PROBABILITY = 0.01;
const REPLACEMENT_CHARACTERS = "✴⦧⦖";
function getRandomlyReplacedText(text) {
if (REPLACEMENT_PROBABILITY === 0) {
return text;
}
const replacementCharacters = REPLACEMENT_CHARACTERS.split("").sort(
() => 0.5 - Math.random()
);
return text
.split("")
.map((originalCharacter) => {
return Math.random() > REPLACEMENT_PROBABILITY
? originalCharacter
: replacementCharacters.length
? replacementCharacters.shift()
: originalCharacter;
})
.join("");
}
function main() {
const lines = readFileSync("./input.txt").toString().split("\n");
const subtitlesWithMetadata = [];
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
const endTimePrevious = index
? subtitlesWithMetadata[index - 1].endTime
: 0;
const isPreviousLineEmpty = index && !lines[index - 1];
const startTime = endTimePrevious + (isPreviousLineEmpty ? 1500 : 0);
subtitlesWithMetadata.push({
startTime,
endTime: startTime + (line ? 3000 : 0),
content: line,
});
}
const srtSubtitles = subtitlesWithMetadata
.filter(({ content }) => content)
.map(
({ startTime, endTime, content }, index) => `${index + 1}
${getFormattedTime(startTime)} --> ${getFormattedTime(endTime)}
${getRandomlyReplacedText(content)}`
)
.join("\n\n");
writeFileSync(
`./output-${new Date().toISOString().replace(/:/g, "-")}.srt`,
srtSubtitles,
"utf-8"
);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment