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'); // Define your languages and codes 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' }, // Add your other languages and codes here... ]; // Function to populate the dropdown options function populateDropdown(select, options) { options.forEach((option) => { const optionElem = document.createElement('option'); optionElem.value = option.code; optionElem.text = option.name; select.add(optionElem); }); } // Call the function to populate dropdown options 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 { // Change placeholder text to "Translating..." outputText.placeholder = 'Translating...'; let sourceLanguage; // Check if Auto Detect is selected for source language 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; } // Check if Auto Detect is selected for target language 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; // Update placeholder with the translated text outputText.placeholder = translatedText; } catch (error) { console.error(error); outputText.placeholder = 'An error occurred. Please try again.'; } }); });