Giter Club home page Giter Club logo

potrans's Introduction

Packagist Version Packagist License Packagist Downloads

PO file translator

Potrans it's PHP command line tool for automatic translation of Gettext PO file with Google Translator or DeepL Translator.

Google Translator

bin/potrans google --help
Description:
  Translate PO file with Google Translator API

Usage:
  google [options] [--] <input> [<output>]

Arguments:
  input                          Input PO file path
  output                         Output PO, MO files directory [default: "~/Downloads"]

Options:
      --from=FROM                Source language (default: en) [default: "en"]
      --to=TO                    Target language (default: cs) [default: "cs"]
      --force                    Force re-translate including translated sentences
      --wait=WAIT                Wait between translations in milliseconds [default: false]
      --credentials=CREDENTIALS  Path to Google Credentials file [default: "./credentials.json"]
      --project=PROJECT          Google Cloud Project ID [default: project_id from credentials.json]
      --location=LOCATION        Google Cloud Location [default: "global"]
      --translator[=TRANSLATOR]  Path to custom translator instance
      --cache|--no-cache         Load from cache or not
  -h, --help                     Display help for the given command. When no command is given display help for the list command
  -q, --quiet                    Do not output any message
  -V, --version                  Display this application version
      --ansi|--no-ansi           Force (or disable --no-ansi) ANSI output
  -n, --no-interaction           Do not ask any interactive question
  -v|vv|vvv, --verbose           Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Example commands

Follow command will translate whole content of tests/example-cs_CZ.po from English (default) to Czech language (default):

bin/potrans google tests/example-cs_CZ.po ~/Downloads \
  --credentials=your-credentials-file.json

You can also change source and target language with --form and --to parametters:

bin/potrans google tests/example-cs_CZ.po ~/Downloads \
  --credentials=your-credentials-file.json \
  --from=en \
  --to=de

Google Translate API Pricing

Google Translate API pricing is based on usage. Translation usage is calculated in millions of characters (M), where 1 M = 10^6 characters. For more information, see the Pricing FAQ.

Getting Google Translation Credentials

  1. Open Google Cloud Console website
  2. Create a new Project (or select existing one)
  3. Search for translate API and enable it then
  4. Go to IAM & Admin > Service Accounts and click to + Create service account
  5. Chose Service account name and Service account ID and click to Create and continue
  6. Grant this service account access to project and add follow roles Cloud Translation API Editor, AutoML Editor
  7. Create new Keys and download credentials JSON file

You can watch it here:

DeepL Translator

bin/potrans deepl --help
Description:
  Translate PO file with DeepL Translator API

Usage:
  deepl [options] [--] <input> [<output>]

Arguments:
  input                          Input PO file path
  output                         Output PO, MO files directory [default: "~/Downloads"]

Options:
      --from=FROM                Source language (default: en) [default: "en"]
      --to=TO                    Target language (default: cs) [default: "cs"]
      --force                    Force re-translate including translated sentences
      --wait=WAIT                Wait between translations in milliseconds [default: false]
      --apikey=APIKEY            Deepl API Key
      --translator[=TRANSLATOR]  Path to custom translator instance
      --cache|--no-cache         Load from cache or not
  -h, --help                     Display help for the given command. When no command is given display help for the list command
  -q, --quiet                    Do not output any message
  -V, --version                  Display this application version
      --ansi|--no-ansi           Force (or disable --no-ansi) ANSI output
  -n, --no-interaction           Do not ask any interactive question
  -v|vv|vvv, --verbose           Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Example commands

bin/potrans deepl tests/example-cs_CZ.po ~/Downloads --apikey=123456

DeepL Translator API pricing

DeepL translator API pricing is based on monthly subscription. There is max. 500,000 characters/month for free.

For more information visit https://www.deepl.com/pro-api

Getting Api Key

  1. Register free Account
  2. Visit Account summary
  3. Search for Authentication Key for DeepL API

Install

composer require --dev om/potrans

Custom translator

If you need to use a custom translator that behaves differently than the original translator. You have the option to use the --translator parameter like follow:

./bin/potrans deepl ./tests/example-cs_CZ.po ~/Downloads \
    --translator=path/to/my/CustomTranslator.php \
    --apikey=123456

PHP file should contain implementation of Translator interface and should return new instance:

<?php
class CustomTranslator implements \potrans\translator\Translator {
  // TODO add your code
}

return new CustomTranslator(); 

You can find an example custom translator in the file DeepLTranslatorEscaped.php

Potrans development

  1. Install composer curl -s http://getcomposer.org/installer | php
  2. Run composer install for install all dependencies
  3. Install PHP Curl extension (curl and json PHP extensions)

For more information about Composer visit: https://getcomposer.org

If you had "command not found: potrans" return, just run the command like this: php bin/potrans and will run without problems.

Troubleshooting

cURL error: SSL certificate issue (Google Translate only)

You may encounter a problem caused by cURL like follow:

cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)

There is missing issuer certificate cacert.pem file and curl won't verify SSL requests:

  1. Download http://curl.haxx.se/ca/cacert.pem
  2. Save is somewhere e.g. /usr/local/etc/cacert.pem
  3. Update your php.ini with following:
curl.cainfo = "/usr/local/etc/cacert.pem"
openssl.cafile = "/usr/local/etc/cacert.pem"

You can verify it with phpinfo() or php --info. Read more detailed instruction here.

Links

potrans's People

Contributors

andreimiculita avatar cripterhack avatar leonardcj avatar ozzyczech avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

potrans's Issues

Known Fatal error with join() function

There is an issue with join() function https://www.php.net/manual/en/function.join.php

Waiting for merge PR: wp-cli/php-cli-tools#142

vendor/bin/potrans --apikey "123456"  --input ./tests/example-cs_CZ.po --verbose --output ./tests/out.po

Fatal error: Uncaught TypeError: join(): Argument #2 ($array) must be of type ?array, string given in /Volumes/Work/test/vendor/wp-cli/php-cli-tools/lib/cli/Arguments.php:485
Stack trace:
#0 /Volumes/Work/test/vendor/wp-cli/php-cli-tools/lib/cli/Arguments.php(485): join(Array, ' ')
#1 /Volumes/Work/test/vendor/wp-cli/php-cli-tools/lib/cli/Arguments.php(401): cli\Arguments->_parseOption(Object(cli\arguments\Argument))
#2 /Volumes/Work/test/vendor/om/potrans/src/potrans.php(44): cli\Arguments->parse()
#3 /Volumes/Work/test/vendor/om/potrans/bin/potrans(3): require('/Volumes/Work/t...')
#4 {main}
  thrown in /Volumes/Work/test/vendor/wp-cli/php-cli-tools/lib/cli/Arguments.php on line 485

PS: can be temporary fixed by swapping args in vendor/wp-cli/php-cli-tools/lib/cli/Arguments.php on line 485

Invalid path to autoload.php

I've installed potrans with composer require --dev om/potrans:dev-master, and it installed to my project's vendor directory at ./lib/vendor/om/potrans/. When I run ./lib/vendor/om/potrans/bin/potrans it throws the following errors because it is unable to find the autoload.php script:

Warning: require_once(/Users/me/src/lda-prenotare/lib/vendor/om/potrans/src/../vendor/autoload.php): failed to open stream: No such file or directory in /Users/q/src/lda-prenotare/lib/vendor/om/potrans/src/potranscli.php on line 12

Fatal error: require_once(): Failed opening required '/Users/me/src/lda-prenotare/lib/vendor/om/potrans/src/../vendor/autoload.php' (include_path='.') in /Users/me/src/lda-prenotare/lib/vendor/om/potrans/src/potranscli.php on line 12

The path to my composer autoload.php file is ./lib/vendor/autoload.php.

The fix would be to change line 12 in om/potrans/src/potranscli.php from:

require_once __DIR__ . '/../vendor/autoload.php';

to:

require_once __DIR__ . '/../../../autoload.php';

Command "newsletter-es_AR.po" is not defined

When I try to run potrans, it doesn't get the credentials :

javier@jm:~/proyectos/utilitarios/traducciones/potrans$ php bin/potrans google newsletter-es_AR.po /tmp/translated --cedentials=fast-flight-404720-e573841b9844.json --from=en --to=es -vvv

In ArgvInput.php line 223:

[Symfony\Component\Console\Exception\RuntimeException]
The "--cedentials" option does not exist.

Exception trace:
at /home/javier/proyectos/utilitarios/traducciones/potrans/vendor/symfony/console/Input/ArgvInput.php:223
Symfony\Component\Console\Input\ArgvInput->addLongOption() at /home/javier/proyectos/utilitarios/traducciones/potrans/vendor/symfony/console/Input/ArgvInput.php:150
Symfony\Component\Console\Input\ArgvInput->parseLongOption() at /home/javier/proyectos/utilitarios/traducciones/potrans/vendor/symfony/console/Input/ArgvInput.php:85
Symfony\Component\Console\Input\ArgvInput->parseToken() at /home/javier/proyectos/utilitarios/traducciones/potrans/vendor/symfony/console/Input/ArgvInput.php:74
Symfony\Component\Console\Input\ArgvInput->parse() at /home/javier/proyectos/utilitarios/traducciones/potrans/vendor/symfony/console/Input/Input.php:56
Symfony\Component\Console\Input\Input->bind() at /home/javier/proyectos/utilitarios/traducciones/potrans/vendor/symfony/console/Command/Command.php:285
Symfony\Component\Console\Command\Command->run() at /home/javier/proyectos/utilitarios/traducciones/potrans/vendor/symfony/console/Application.php:1078
Symfony\Component\Console\Application->doRunCommand() at /home/javier/proyectos/utilitarios/traducciones/potrans/vendor/symfony/console/Application.php:324
Symfony\Component\Console\Application->doRun() at /home/javier/proyectos/utilitarios/traducciones/potrans/vendor/symfony/console/Application.php:175
Symfony\Component\Console\Application->run() at /home/javier/proyectos/utilitarios/traducciones/potrans/src/commands/index.php:22
require() at /home/javier/proyectos/utilitarios/traducciones/potrans/bin/potrans:3

google [--from FROM] [--to TO] [--force] [--wait WAIT] [--credentials CREDENTIALS] [--project PROJECT] [--location LOCATION] [--translator [TRANSLATOR]] [--cache|--no-cache] [--] []

javier@jm:~/proyectos/utilitarios/traducciones/potrans$

Any clue to help me find a solution will be appreciated. Thanks.

Error "Server Error #403: "

Hello OzzyCzech

I get the following:

$potrans -k -i ~/Downloads/health_inpatient.pot -o health_inpatient-id.pot -f en -t id
Translating : 345 entries from en to id
Error "Server Error #403:

Arch linux is now on php version 7
php -v
PHP 7.0.5 (cli) (built: Mar 29 2016 18:07:10) ( NTS )

But I also have:
$ php56 -v
PHP 5.6.20 (cli) (built: Apr 23 2016 11:45:06)

I followed the instructions for both php and php56 but in both cases the error is the same.

Changing the install slightly, I then changed 'composer install' to php56 composer.phar install.
Still the error was the same

Thanks for the app by the way.

Best wishes

Allow using non-free DeepL api endpoint [bug]

The endpoint used for DeepL Pro is different from the one used for free accounts.

i.e. instead of

curl_setopt($curl, CURLOPT_URL, 'https://api-free.deepl.com/v2/translate');

it should be
https://api.deepl.com/v2/translate

Currently, trying to use the free endpoint with an authentication key for a pro account results in an error (which unfortunately causes potrans to fail silently and generate all translations in the from language).

There should be a flag to choose which endpoint to use, or even have potrans automatically change endpoints if one of them fails.

Cache doesn't take into account changed language

Hi, thanks for this tool! Unfortunately, trying to run it for separate languages without disabling the cache doesn't work. This is because it reuses the previous language's cache, even though the --to= option was changed to something else.

Feature recommendations

Currently I'm working on very similar project to this project.
I have recommendations if you didn't already made:

  • Saving old translations in another file and only translate new words. So this can save money for paid Google service.
  • Not connecting translate API for every string. Making 20-30 string chunks and request 20 string translate at a time. So lowering network request.
  • Making an option for full translate of po file or translating only new words.

Error "Server Error #400: "

Hi I enabled Cloud Translation API and created an API key to try but I'm getting Error "Server Error #400: "

Add option for DeepL to ignore certain substrings matched by regex

Original string:
"I have $number$ apples in my $recipient$"
Desired translated string:
"Tengo $number$ manzanas en mi $recipient$"
Actual translated string:
"Tengo $número$ manzanas en mi $recipiente$"

The issue is the DeepL is also translating the $number$ and $recipient$, which I would like to specify as ignored (for example with the regex \$[^$]+\$)

Under the hood, you would search for the specified regex, add opening/closing XML tags around matching substrings with preg_replace (such as <keep></keep>), and specify those tags when doing the API call: https://www.deepl.com/docs-api/xml/ignored-tags/ And then remove the tags after receiving the translated string.

Argument #1 ($translation) must be of type string, null given

ERROR: Gettext\Translation::translate(): Argument #1 ($translation) must be of type string, null given, called in vendor\om\potrans\src\commands\DeepLTranslatorCommand.php on line 121 on vendor\gettext\gettext\src\Translation.php at 173

if you run a command like:
php vendor/bin/potrans deepl --apikey=XXX --from=en-us --to=sv test.po out

I accidentally wrote en-us in the from

Correct autoload?

On line 12 of potranscli.php it references this:

require_once __DIR__ . '/../vendor/autoload.php';

But that has no reference, there is no autoloader.php file inside of the root of the project. Unless I'm missing something, either you need to add one or use the default one with composer.

The vendor root is at least three levels above this one, (vendor/om/src/potranscli.php), so the correct path should be:

require_once __DIR__ . '/../../../autoload.php';

Error "Server Error #403: "

Hello,
I followed all needed steps to set up POTRANS but when I run it like this :
php bin/potrans -k 1234567890 -i fr_FR.po -o fr_FR_trans.po -f en -t fr
Translating : 1512 entries from en to fr

It dumps this error:
Error "Server Error #403: "

What does it mean and how to fix this?
I tried the 'sleep(1)' hint from another thread but this does not help at all.

Thanks for your precious help
Hacen

read deepl apikey from file or env

I dont like to check in my apikey to me repo in order to automate the translations using deepl
could there be an option to read the apikey from either env or a file?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.