AncientBrain.createWorld("Translation Comparison", function () {
// UI elements: Text input and language dropdown
var textInput = AncientBrain.createElement("input");
textInput.setAttribute("placeholder", "Enter text here");
var languageDropdown = AncientBrain.createElement("select");
languageDropdown.innerHTML = `
<option value="es">Spanish</option>
<option value="fr">French</option>
<option value="de">German</option>
<option value="it">Italian</option>
`;
var translateButton = AncientBrain.createElement("button");
translateButton.textContent = "Translate";
// Results display
var googleResult = AncientBrain.createElement("p");
var deepLResult = AncientBrain.createElement("p");
// Append all UI elements to the world
AncientBrain.addElement(textInput);
AncientBrain.addElement(languageDropdown);
AncientBrain.addElement(translateButton);
AncientBrain.addElement(googleResult);
AncientBrain.addElement(deepLResult);
// Function to send translation request to Google Translation API
async function fetchGoogleTranslation(text, targetLanguage) {
const apiKey = "YOUR_GOOGLE_API_KEY"; // Replace with your actual API key
const url = `https://translation.googleapis.com/language/translate/v2?key=${apiKey}`;
const response = await fetch(url, {
method: "POST",
body: JSON.stringify({
q: text,
target: targetLanguage
}),
headers: {
"Content-Type": "application/json"
}
});
const data = await response.json();
return data.data.translations[0].translatedText;
}
// Function to send translation request to DeepL API
async function fetchDeepLTranslation(text, targetLanguage) {
const apiKey = "YOUR_DEEPL_API_KEY"; // Replace with your actual API key
const url = `https://api-free.deepl.com/v2/translate?auth_key=${apiKey}`;
const response = await fetch(url, {
method: "POST",
body: new URLSearchParams({
text: text,
target_lang: targetLanguage
}),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
const data = await response.json();
return data.translations[0].text;
}
// Handle the translation process
async function handleTranslation() {
const text = textInput.value;
const targetLanguage = languageDropdown.value;
try {
const googleTranslation = await fetchGoogleTranslation(text, targetLanguage);
const deepLTranslation = await fetchDeepLTranslation(text, targetLanguage);
// Display the results
googleResult.textContent = `Google Translation: ${googleTranslation}`;
deepLResult.textContent = `DeepL Translation: ${deepLTranslation}`;
} catch (error) {
console.error("Error during translation:", error);
}
}
// Add event listener to the Translate button
translateButton.addEventListener("click", handleTranslation);
});