Node JS script to translate SRT file
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I need a small Node JS script to be able to:


Loop through SRT files

Translate each line via the Deepl translate API

Save back the translated text to each row of the SRT

Save the new SRT file locally


Translated sentences should still make sense and not broken when saved back to each row. I can send extra tips if necessary :)

An example SRT file can be found here:
https://file.io/3pJydiGpVuNX

And the Deepl documentation is here: https://www.deepl.com/docs-api/introduction/

Thanks!

The file link 404s. Can you upload to Pastebin instead?
B44ken 28 days ago
Hey, here is the pastebin link https://pastebin.com/mW9BziAe
user0809 28 days ago
@B44ken, did you manage to open the pastebin? :)
user0809 28 days ago
Haha yeah, I guess file.io automatically deletes files once they're viewed as an anonyminity feature.
B44ken 28 days ago
21 days ago

Crowdsource coding tasks.

1 Solution


Hey, here is my solution,

https://drive.google.com/file/d/1e0nelNYlcM01oulkQqioAudOPDOCZ5WE/view

Don't forget to install packages and add your deeply API KEY.
You can also change the path where the srt files located.

npm install bluebird
npm install line-reader
npm install axios

you can set the default target language while running.

node app.js RU
node app.js PL

app.js

const path = './files/';
const filterFileExtension = ".srt";
const apiURL = 'https://api.deepl.com/v1/translate';
const authKey = 'YOUR_DEEPLY_API_KEY';
var targetLang = "PL"

const fs = require('fs');
const readline = require('readline');
const lineReader = require('line-reader');
const Promise = require("bluebird");
const axios = require('axios');
const eachLine = Promise.promisify(lineReader.eachLine);

if (process.argv.length == 3) {
  targetLang = process.argv[2]
}
init();

function init() {
  fs.readdir(path, (err, files) => {
    files.forEach(file => {
      if (file.endsWith(filterFileExtension)) {
        var newFile = { name: file, parts: [] }
        var newLine = {};
        eachLine(path + file, function(line) {
          if (line == "") {
            newFile.parts.push(newLine);
              newLine = {};
          } else {
            if (newLine.num === undefined) newLine.num = line;
            else if (newLine.time === undefined) newLine.time = line;
            else if (newLine.sentences === undefined) {
              newLine.sentences = [line]
            } else {
              newLine.sentences.push(line)
            }
          }
        }).then(() => {
          if (newLine.num !== undefined) {
            newFile.parts.push(newLine);
          }
          translate(newFile)
        });
    }
    });
  });

  function translate(_file) {
    var parts = [];
    var content = "";
    _file.parts.forEach(el => {
      if (el.sentences !== undefined && el.sentences.length > 0) {
        content += el.num + "\r\n";
        content += el.time + "\r\n";
        content += el.sentences.join("\r\n");
        content += "\r\n\r\n";
        if (Buffer.byteLength(content) > 5*1024) {
          parts.push(getApiRequest(content));
          content = ""
        }
      }
    })

    if (content != "") {
      parts.push(getApiRequest(content));
    }
    console.log(`translating ${_file.name} to ${targetLang}`);
    axios.all(parts).then(function(values) {
      var newFileName = path + _file.name.split('.')[0] + '-' + targetLang + '.srt';
      values.forEach(val => {
        fs.appendFileSync(newFileName, val.data.translations[0].text);
      })
      console.log(`completed ${newFileName} to ${targetLang}`);
    });

  }

  function getApiRequest(text) {
    return axios
        .get(apiURL, { params: {
          text: text,
          target_lang: targetLang,
          auth_key: authKey
        }});
  }
}
hey cool solution!
Qdev 23 days ago
I got this error when running the script after installing all the dependencies: (node:4995) UnhandledPromiseRejectionWarning: Error: Request failed with status code 403
user0809 22 days ago
It's probably about API version. I don't have an API account but I've deeply pro account. So it works with v1. You should just change the version and try again. Change v1 to v2 const apiURL = 'https://api.deepl.com/v1/translate'; to const apiURL = 'https://api.deepl.com/v2/translate';
ocanal 22 days ago