Files
video2document/services/modules/replace_speaker/replaceSpeaker.js
T
2026-01-12 19:07:42 +01:00

70 lines
2.4 KiB
JavaScript

const fs = require('fs');
const path = require('path');
const module_exports = {
name: "replace_speaker",
type: "processor",
displayname: "Speaker Name Replacer",
description: "Replaces speaker placeholder names with actual names based on a mapping in HTML files",
async function({ inputHtmlPath, speakerMappingPath }) {
return await this.replaceNames(inputHtmlPath, speakerMappingPath);
},
replaceNames: async function(inputHtmlPath, speakerMappingPath) {
try {
const htmlContent = await fs.promises.readFile(inputHtmlPath, "utf-8");
const mappingData = await fs.promises.readFile(speakerMappingPath, "utf-8");
let speakerMap = {};
try {
const parsed = JSON.parse(mappingData);
if (parsed.speakerId && parsed.speakerName) {
speakerMap[parsed.speakerId] = parsed.speakerName;
} else {
Object.assign(speakerMap, parsed);
}
} catch (e) {
const lines = mappingData.trim().split('\n');
lines.forEach(line => {
const [placeholder, realName] = line.split(',').map(s => s.trim());
if (placeholder && realName) speakerMap[placeholder] = realName;
});
}
let outputContent = htmlContent;
Object.entries(speakerMap).forEach(([placeholder, realName]) => {
const regex = new RegExp(`[\$begin:math:text$\\\\\[\]\?\$\{placeholder\}\[\\$end:math:text$\\]]?`, 'g');
outputContent = outputContent.replace(regex, realName);
});
await fs.promises.writeFile(inputHtmlPath, outputContent, "utf-8");
return inputHtmlPath;
} catch (error) {
console.error("Error replacing speaker names:", error);
throw error;
}
}
};
module.exports = module_exports;
if (require.main === module) {
(async () => {
const args = process.argv.slice(2);
if (args.length < 2) process.exit(1);
const [inputHtmlPath, speakerMappingPath] = args;
if (!fs.existsSync(inputHtmlPath)) process.exit(1);
if (!fs.existsSync(speakerMappingPath)) process.exit(1);
try {
await module_exports.replaceNames(inputHtmlPath, speakerMappingPath);
} catch (err) {
process.exit(1);
}
})();
}