|
document.addEventListener('DOMContentLoaded', function () { |
|
const form = document.querySelector('#translationForm'); |
|
const targetLangSelect = document.querySelector('#target_lang'); |
|
const sourceLangSelect = document.querySelector('#source_lang'); |
|
const userInput = document.querySelector('#userinput'); |
|
const outputText = document.querySelector('#output'); |
|
|
|
|
|
const languages = [ |
|
{ name: 'Swahili', code: 'swh_Latn' }, |
|
{ name: 'Kikuyu', code: 'kik_Latn' }, |
|
{ name: 'Spanish', code: 'spa_Latn' }, |
|
{ name: 'French', code: 'fra_Latn' }, |
|
{ name: 'Amharic', code: 'amh_Ethi' }, |
|
{ name: 'English', code: 'eng_Latn' }, |
|
|
|
]; |
|
|
|
|
|
function populateDropdown(select, options) { |
|
options.forEach((option) => { |
|
const optionElem = document.createElement('option'); |
|
optionElem.value = option.code; |
|
optionElem.text = option.name; |
|
select.add(optionElem); |
|
}); |
|
} |
|
|
|
|
|
populateDropdown(targetLangSelect, languages); |
|
populateDropdown(sourceLangSelect, [{ name: 'Auto Detect', code: 'auto' }, ...languages]); |
|
|
|
form.addEventListener('submit', async (e) => { |
|
e.preventDefault(); |
|
|
|
const targetLang = targetLangSelect.value; |
|
const sourceLang = sourceLangSelect.value; |
|
|
|
try { |
|
|
|
outputText.placeholder = 'Translating...'; |
|
|
|
let sourceLanguage; |
|
|
|
|
|
if (sourceLang === 'auto') { |
|
const detectionResponse = await fetch('https://lewiskimaru-helloworld.hf.space/translate_detect/', { |
|
method: 'POST', |
|
headers: { |
|
'Content-Type': 'application/json' |
|
}, |
|
body: JSON.stringify({ |
|
userinput: userInput.value, |
|
target_lang: targetLang |
|
}) |
|
}); |
|
|
|
const detectionData = await detectionResponse.json(); |
|
sourceLanguage = detectionData.source_language; |
|
} else { |
|
sourceLanguage = sourceLang; |
|
} |
|
|
|
|
|
const targetLanguage = targetLang === 'auto' ? 'eng_Latn' : targetLang; |
|
|
|
const translationResponse = await fetch('https://lewiskimaru-helloworld.hf.space/translate_enter/', { |
|
method: 'POST', |
|
headers: { |
|
'Content-Type': 'application/json' |
|
}, |
|
body: JSON.stringify({ |
|
userinput: userInput.value, |
|
target_lang: targetLanguage, |
|
source_lang: sourceLanguage |
|
}) |
|
}); |
|
|
|
const translatedText = (await translationResponse.json()).translated_text; |
|
|
|
|
|
outputText.placeholder = translatedText; |
|
|
|
} catch (error) { |
|
console.error(error); |
|
outputText.placeholder = 'An error occurred. Please try again.'; |
|
} |
|
}); |
|
}); |
|
|