Spaces:
Running
Running
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Sema API Integration Example</title> | |
</head> | |
<body> | |
<h1>Translate and Detect Source Language</h1> | |
<form action="#" method="post"> | |
<label for="userinput">Enter text to translate:</label> | |
<input type="text" id="userinput" name="userinput"> | |
<label for="target_lang">Enter target language:</label> | |
<input type="text" id="target_lang" name="target_lang"> | |
<input type="submit" value="Translate"> | |
</form> | |
<div id="output"></div> | |
<script> | |
const form = document.querySelector('form'); | |
const targetLangInput = document.querySelector('#target_lang'); | |
const outputDiv = document.querySelector('#output'); | |
form.addEventListener('submit', async (e) => { | |
e.preventDefault(); | |
const userInput = document.querySelector('#userinput').value; | |
const targetLang = targetLangInput.value || 'swh_Latn'; | |
try { | |
const response = await fetch('https://kamau1-sema-api.hf.space/translate_detect/', { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json' | |
}, | |
body: JSON.stringify({ | |
userinput: userInput, | |
target_lang: targetLang | |
}) | |
}); | |
const data = await response.json(); | |
const sourceLanguage = data.source_language; | |
const translatedText = data.translations[0].text; | |
outputDiv.innerHTML = ` | |
<p><strong>Output:</strong></p> | |
<p>Source Language: ${source_language}</p> | |
<p>Translated Text: ${translated_text}</p> | |
`; | |
} catch (error) { | |
console.error(error); | |
outputDiv.textContent = 'An error occurred while translating the text. Please check the input and try again.'; | |
} | |
}); | |
</script> | |
</body> | |
</html> | |