-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
212 lines (184 loc) · 8.28 KB
/
Copy pathindex.js
File metadata and controls
212 lines (184 loc) · 8.28 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
const fs = require("fs");
const path = require("path");
const { JSDOM } = require("jsdom");
const translate = require("google-translate-api-x");
const unfilteredlanguages = require("./languages.json");
const inputFolder = "./en"; // Input folder with HTML files
const outputFolder = "./"; // Output folder for translated files
// Cache to avoid redundant translations
const translationCache = new Map();
// Function to translate text with caching
async function translateText(text, lang) {
const cacheKey = `${lang}:${text}`;
if (translationCache.has(cacheKey)) {
return translationCache.get(cacheKey);
}
// Avoid translating "evaluating.tools"
if (text.toLowerCase().includes("evaluating.tools")) {
const parts = text.split("evaluating.tools");
const translatedParts = await Promise.all(
parts.map((part, index) =>
index === parts.length - 1
? Promise.resolve(part) // Keep the domain part unchanged
: translate(part.trim(), { to: lang, forceTo: true }).then((res) => res.text)
)
);
const result = translatedParts.join("evaluating.tools");
translationCache.set(cacheKey, result);
return result;
}
// Translate the text and cache it
try {
const result = await translate(text.trim(), { to: lang, forceTo: true });
translationCache.set(cacheKey, result.text);
return result.text;
} catch (err) {
console.error(`Error translating text "${text}" to "${lang}": ${err.message}`);
return text; // Fallback to original text if translation fails
}
}
// Function to construct canonical URLs
function constructCanonicalUrl(relativePath, lang) {
let cleanPath = relativePath.replace(/\\/g, "/").replace(/\/+$/, ""); // Normalize path
if (cleanPath === "." || cleanPath === "") cleanPath = ""; // Root path
else if (!cleanPath.endsWith(".html")) cleanPath += "/"; // Add trailing slash if needed
return `https://evaluating.tools/${lang}/${cleanPath}`;
}
// Function to translate an individual element's text
async function translateElementText(element, lang) {
if (!element.textContent.trim() || element.textContent.trim().startsWith("©") || element.textContent.toLowerCase().includes("evaluating.tools")) {
return;
}
try {
if (element.childNodes && element.childNodes.length > 0) {
for (const child of element.childNodes) {
if (child.nodeType === 3) { // Node.TEXT_NODE
const translatedText = await translateText(child.nodeValue.trim(), lang);
child.nodeValue = translatedText;
}
}
} else {
const translatedText = await translateText(element.textContent.trim(), lang);
element.textContent = translatedText;
}
} catch (err) {
console.error(`Error translating element text "${element.textContent}" to "${lang}": ${err.message}`);
}
}
// Function to handle <a> elements
async function translateAnchorElement(element, lang) {
const originalHref = element.getAttribute("href");
if (originalHref && originalHref.includes("/en/")) {
const updatedHref = originalHref.replace("/en/", `/${lang}/`);
element.setAttribute("href", updatedHref);
}
const text = element.textContent.trim();
if (text) {
const translatedText = await translateText(text, lang);
element.textContent = translatedText;
}
}
// Translate the content of an HTML file
async function translateHTML(filePath, relativePath) {
const content = fs.readFileSync(filePath, "utf8");
const originalDom = new JSDOM(content);
const document = originalDom.window.document;
const elementsQuery = "h1, h2, h3, h4, span, a, button, p, label, option, div";
// Update alternates for all languages
for (const langObj of unfilteredlanguages.data) {
const lang = langObj.code;
const existingAltLink = document.querySelector(`link[rel="alternate"][hreflang="${lang}"]`);
if (!existingAltLink) {
const linkTag = document.createElement("link");
linkTag.setAttribute("rel", "alternate");
linkTag.setAttribute("hreflang", lang);
linkTag.setAttribute("href", constructCanonicalUrl(relativePath, lang));
document.head.appendChild(linkTag);
}
}
// Loop through languages to create new files
for (const langObj of unfilteredlanguages.data) {
if (!langObj.createnew) continue;
const lang = langObj.code;
try {
const translatedDom = new JSDOM(content);
const translatedDocument = translatedDom.window.document;
const htmlTag = translatedDocument.querySelector("html");
if (htmlTag) htmlTag.setAttribute("lang", lang);
let canonicalLink = translatedDocument.querySelector('link[rel="canonical"]');
if (!canonicalLink) {
canonicalLink = translatedDocument.createElement("link");
translatedDocument.head.appendChild(canonicalLink);
}
canonicalLink.setAttribute("rel", "canonical");
canonicalLink.setAttribute("href", constructCanonicalUrl(relativePath, lang));
// Translate meta tags: og:title, og:description, og:url
const metaOgTitle = translatedDocument.querySelector('meta[property="og:title"]');
if (metaOgTitle) {
const originalTitle = metaOgTitle.getAttribute("content");
const translatedTitle = await translateText(originalTitle, lang);
metaOgTitle.setAttribute("content", translatedTitle);
}
const metaOgDescription = translatedDocument.querySelector('meta[property="og:description"]');
if (metaOgDescription) {
const originalDescription = metaOgDescription.getAttribute("content");
const translatedDescription = await translateText(originalDescription, lang);
metaOgDescription.setAttribute("content", translatedDescription);
}
const metaOgUrl = translatedDocument.querySelector('meta[property="og:url"]');
if (metaOgUrl) {
metaOgUrl.setAttribute("content", constructCanonicalUrl(relativePath, lang));
}
// Translate <meta name="title"> and <meta name="description">
const metaTitle = translatedDocument.querySelector('meta[name="title"]');
if (metaTitle) {
const originalTitle = metaTitle.getAttribute("content");
const translatedTitle = await translateText(originalTitle, lang);
metaTitle.setAttribute("content", translatedTitle);
}
const metaDescription = translatedDocument.querySelector('meta[name="description"]');
if (metaDescription) {
const originalDescription = metaDescription.getAttribute("content");
const translatedDescription = await translateText(originalDescription, lang);
metaDescription.setAttribute("content", translatedDescription);
}
const elements = translatedDocument.querySelectorAll(elementsQuery);
for (const element of elements) {
if (element.tagName.toLowerCase() === "a") {
await translateAnchorElement(element, lang);
} else {
await translateElementText(element, lang);
}
}
const langFolder = path.join(outputFolder, lang, relativePath);
fs.mkdirSync(langFolder, { recursive: true });
const outputFilePath = path.join(langFolder, path.basename(filePath));
fs.writeFileSync(outputFilePath, translatedDom.serialize(), "utf8");
console.log(`Translated: ${filePath} -> ${outputFilePath}`);
} catch (err) {
console.error(`Error processing file ${filePath} for language ${lang}: ${err.message}`);
}
}
}
// Recursive function to process folders
async function processFolder(folderPath, relativePath = "") {
const entries = fs.readdirSync(folderPath, { withFileTypes: true });
for (const entry of entries) {
const entryPath = path.join(folderPath, entry.name);
const newRelativePath = path.join(relativePath, entry.name);
if (entry.isDirectory()) {
await processFolder(entryPath, newRelativePath);
} else if (entry.isFile() && entry.name.endsWith(".html")) {
await translateHTML(entryPath, path.dirname(newRelativePath));
}
}
}
// Main function
(async function main() {
if (!fs.existsSync(inputFolder)) {
console.error("Input folder does not exist.");
return;
}
await processFolder(inputFolder);
console.log("Translation process completed!");
})();