I'm trying to build a gift for my girlfriend, who is Ukrainian and really enjoys watching anime. There aren't many good anime streaming sites with Ukrainian subtitles, so I want to create a real-time translator app that can translate English subtitles into Ukrainian for the site we usually use. I've started working on this using Tampermonkey, but honestly, I'm struggling and not making much progress. Here's my current code:
```javascript
(function () {
'use strict';
let lastSubtitle = '';
async function translate(text) {
try {
const response = await fetch('https://de.libretranslate.com/translate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
q: text,
source: 'en',
target: 'uk',
format: 'text'
})
});
const data = await response.json();
return data.translatedText || text;
} catch (err) {
console.error('Translation error:', err);
return text;
}
}
setInterval(async () => {
const subtitleElements = Array.from(document.querySelectorAll('div, span'))
.filter(el => el.innerText && el.innerText.length < 200 && el.offsetParent !== null);
for (const el of subtitleElements) {
const currentText = el.innerText.trim();
if (currentText && currentText !== lastSubtitle && /^[a-zA-Z0-9 ,.'"-?!]+$/.test(currentText)) {
lastSubtitle = currentText;
const translated = await translate(currentText);
el.innerText = `${currentText}n${translated}`;
console.log('Subtitle translated:', currentText, '→', translated);
break;
}
}
}, 1500);
})();
```
I'd love any tips or guidance you might have! Thanks!
2 Answers
What a thoughtful idea for a gift! Instead of reversing the whole anime site, I suggest checking out anime torrents. They typically have separate subtitle files that you could parse and send to a translation API. It might be a lot easier than what you’re trying to do now!
I think your project is a really sweet gesture! As a software developer, I can certainly help out with your code if you need more specific advice. Just let me know!
I really appreciate that! I might take you up on that offer.
Yeah, there are sites where you can download these subtitle files. It could make your process much simpler, but just a heads up, it might end up being too much work for her, and you want to make it enjoyable for her too!