py-translate

py-translate is a CLI Tool for Google Translate written in Python!


Author:Sang Han 2014
License:Apache Software License v2
Version:v1.0.2

Quickstart Guide

py-translate

Documentation github travis pypi Wheel

A Translation Tool for Humans

Translate Lewis Carroll: Alice in Wonderland

Translate Lewis Carroll: Alice in Wonderland


The end goal is a simple application for translating text in the terminal. Text can be generated interactively or programmatically in the shell environment. Through command line arguments, file descriptors or pipes generating translated output that can be piped to a file or displayed on the terminal.

Features

  • Made for Python 3 but still works on Python 2
  • Fast and easy to install, easy to use
  • Supports translation from any language
  • Highly composable interface, the power of Unix pipes and filters.
  • Simple API and documentation

Installation

From PyPI with pip (easy)
$ pip install py-translate
From Source at Github
  • Clone the repository
$ git clone https://github.com/jjangsangy/py-translate.git
  • Install with setup.py
$ python setup.py install

Usage

translate [--flags] [source] dest
Arguments
Positional  
dest Destination language code
source Source language code
Optional  
-h,–help Show this help message and exit
-v, –version Show program’s version number and exit
-l,–list [code] Enumerate the name of country and language code pair.
  [ Optionally specify output language format ]
–translit Print out the transliteration of the text

Examples

Hello World from English to Traditional Chinese

$ translate en zh-TW <<< 'Hello World!'
你好世界!
Hello World

Hello World

  • Just as easily specify a source language by providing it as first argument
# Translate Hello from French to English
$ translate fr en <<< 'Bonjour, comment allez-vous!'
Hello, how are you?
Smart Language Detection

Omitting the source language will try to detect it based on the text content

$ translate fr <<< 'I think therefore I am'
Je pense donc je suis
Romanified Transliteration
$ translate --translit en ko <<< 'Want to fight!'
ssaugo sip-eo!

$ translate --translit en zh-TW <<< 'Kidding, we should be friends'
Kāiwánxiào, wǒmen yīnggāi shì péngyǒu
Redirect from File
$ translate zh-TW < 'alice.txt'

阿麗思道:「你不是說你要告訴你的歷史嗎?告訴我你為甚麼恨—那個—那些—C和D,」
她末了兩個字母輕輕兒地說的,怕回來又得罪了牠。

那老鼠對著阿麗思嘆了一口氣道,「唉﹗我的身世說來可真是又長又苦又委屈呀—」

阿麗思聽了,瞧著那老鼠的尾巴說,「你這尾是曲啊﹗可是為甚麼又叫它苦呢﹗」
她就一頭聽著那老鼠說話,一頭在在心上納悶,所以她聽的那老鼠講的「尾曲」
的歷史是差不多像這個樣了的
....
Chaining together Pipes
# Multiple Chaining
$ echo 'What is love?' | translate en zh-TW | translate zh-TW ko | translate ko fr | translate fr en
What is love?
Be Creative!
# Grocery List
$ cat << BUY | translate ko
Celery
Milk
Eggs
Bread
Cereal
BUY

셀러리
우유
달걀
빵
시리얼

Support

Here’s a list of Python platforms that are officially supported.

  • Python 3.4
  • Python 3.3
  • Python 3.2
  • Python 2.7
  • Python 2.6
  • PyPy 2 (Latest)
  • PyPy 3 (latest)

Documentation

Find the latest documentation http://pythonhosted.org/py-translate/

Contribute

  1. Fork us on Github.
  2. Find a bug? Implemented a new feature? Send a pull request to get it merged and published.
  3. Feel free to send an e-mail to the code maintainer for questions or help regarding the codebase. jjangsangy@gmail.com

Overview

Examples

Basic Usage

$ translate zh-TW <<< "Hello World!"
你好世界!

$ translate ko <<< "Goodbye!"
안녕히 가세요!

Redirect from File

$ translate zh-TW < "alice.txt"

阿麗思道:「你不是說你要告訴你的歷史嗎?告訴我你為甚麼恨—那個—那些—C和D,」
她末了兩個字母輕輕兒地說的,怕回來又得罪了牠。

那老鼠對著阿麗思嘆了一口氣道,「唉﹗我的身世說來可真是又長又苦又委屈呀—」

阿麗思聽了,瞧著那老鼠的尾巴說,「你這尾是曲啊﹗可是為甚麼又叫它苦呢﹗」
她就一頭聽著那老鼠說話,一頭在在心上納悶,所以她聽的那老鼠講的「尾曲」
的歷史是差不多像這個樣了的

Unix Pipes!

# Redirect any output through a unix pipe.
$ python --help | translate fr
D'autres variables d'environnement

PYTHONSTARTUP: le fichier exécuté au démarrage interactif (pas par défaut)
PYTHONPATH: ':'-liste de répertoires séparés préfixés à la
   module par défaut chemin de recherche. Le résultat est sys.path.
PYTHONHOME: Annuaire <prefix> suppléant (ou <prefix> <exec_prefix>).
PYTHONCASEOK: ignorer la casse dans les états d'importation» (Windows).
PYTHONIOENCODING: Codage [: erreurs] utilisés pour stdin / stdout / stderr.
PYTHONHASHSEED: si cette variable est définie à aléatoire, l'effet est le même
   comme spécifiant l'option-R: une valeur aléatoire est utilisée pour ensemencer les hashs de
   str, octets et objets datetime. Il peut également être défini à un nombre entier
   dans l'intervalle [0,4294967295] pour obtenir des valeurs de hachage avec une graine prévisible.

Be Creative

# A "Here-String" Grocery List
$ cat <<- GROCERY_LIST | translate ko
     Celery
     Milk
     Eggs
     Bread
     Cereal
GROCERY_LIST

셀러리
우유
달걀
빵
시리얼

Chaining together Pipes

# Translate Telephone!
$ echo 'What is love?' | translate zh-TW | translate ko | translate fr | translate en
What is love?

Arguments

Requires at least one command line argument for the destination language. If no command line arguments are passed, an error message will be passed.

$ translate | "Error! No Arguments"
usage: translate [-h] [-v] [-l [code]] [source] dest
translate: error: the following arguments are required: dest

See Usage section for usage information

Language Codes

Use the -l option to see all the possible language codes.

$ translate -l

Specify the output format by language code

$ translate -l zh-TW
Language Code
Afrikaans af
Albanian sq
Arabic ar
Azerbaijani az
Basque eu
Belarusian be
Bengali bn
Bosnian bs
Bulgarian bg
Catalan ca
Cebuano ceb
Chinese (Simplified) zh
Chinese (Traditional) zh-TW
Croatian hr
Czech cs
Danish da
Dutch nl
English en
Esperanto eo
Estonian et
Filipino tl
Finnish fi
French fr
Galician gl
Georgian ka
German de
Greek el
Gujarati gu
Haitian Creole ht
Hebrew iw
Hindi hi
Hmong hmn
Hungarian hu
Icelandic is
Indonesian id
Irish ga
Italian it
Japanese ja
Javanese jw
Kannada kn
Khmer km
Korean ko
Lao lo
Latin la
Latvian lv
Lithuanian lt
Macedonian mk
Malay ms
Maltese mt
Marathi mr
Norwegian no
Persian fa
Polish pl
Portuguese pt
Romanian ro
Russian ru
Serbian sr
Slovak sk
Slovenian sl
Spanish es
Swahili sw
Swedish sv
Tamil ta
Telugu te
Thai th
Turkish tr
Ukrainian uk
Urdu ur
Vietnamese vi
Welsh cy
Yiddish yi
Language Code
土耳其文 tr
中文(繁體) zh-TW
中文(簡體) zh
丹麥文 da
巴斯克文 eu
日文 ja
爪哇語 jw
加里西亞文 gl
加泰羅尼亞文 ca
卡納達文 kn
布爾文 af
白俄羅斯語 be
立陶宛文 lt
冰島文 is
匈牙利文 hu
印尼文 id
印度文 hi
印度古哈拉地語 gu
西班牙文 es
克羅埃西亞文 hr
希伯來文 iw
希臘文 el
亞塞拜然文 az
孟加拉文 bn
拉丁文 la
拉脫維亞文 lv
法文 fr
波西尼亞 bs
波斯語 fa
波蘭文 pl
芬蘭文 fi
阿拉伯文 ar
阿爾巴尼亞文 sq
俄文 ru
保加利亞文 bg
威爾斯文 cy
苗文 hmn
英文 en
挪威文 no
泰文 th
泰米爾文 ta
泰盧固文 te
海地克里奧文 ht
烏克蘭文 uk
烏爾都語 ur
馬耳他文 mt
馬來文 ms
馬其頓文 mk
馬拉地文 mr
高棉文 km
國際語文 eo
宿霧文 ceb
捷克文 cs
荷蘭文 nl
喬治亞文 ka
斯瓦希里文 sw
斯洛伐克文 sk
斯洛維尼亞文 sl
菲律賓文 tl
越南文 vi
塞爾維亞文 sr
意第緒語 yi
愛沙尼亞文 et
愛爾蘭文 ga
瑞典文 sv
義大利文 it
葡萄牙文 pt
寮文 lo
德文 de
韓文 ko
羅馬尼亞文 ro

Features

  • Simple command line parsing!
  • Written in pure Python!
  • Backwards compatable with Python 2.7
  • Supports all language from Google Translate API
  • The power of Unix pipes and filters
  • Native UTF-8 Support

Installation

From PyPI

  • To install py-translate, simply:
$ pip install py-translate

From Source

  • Installation from the Git source repository.
$ git clone https://github.com/jjangsangy/py-translate.git
  • Use setup.py
$ python setup.py install

OS X Installation

For full installation instructions for OS X, please visit Mac OS X Full Installation

Mac OS X Full Installation

Mac OS X is a great development enviornment for python. However, using the default python installation which comes with the operating system currently (Mavericks 10.9.2), has many issues in terms of interfacing with third party applications.

Before we can get hacking. We will need to do 3 things

  1. Get a C Compiler
    • Install XCode
    • Install GCC using Apples Command Line Tools
  2. Get a Package Manager
    • Install Homebrew
  3. Install Python
    • Install your own copy of Python. No more messing with system copy.
    • Install pip

1. Installing XCode or Command Line Tools

By default, Apple does not package OS X with it’s own C Compiler.

The default way would be to download and install XCode. which is free to anyone with an apple account and can be installed through the App Store.

Another option for Lion, Mountain Lion and Mavericks users, Apple now provides an official Command Line Tools for Xcode package that you can install without needing to install Xcode itself!

You can download it from Apple’s developer site (free registration required) and search for “Command Line Tools”.

command_line_tools

2. Install Homebrew

Once we have installed GCC and/or command line tools installing homebrew is very straightforward.

Open up a terminal window and enter

$ ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

This will install the homebrew package manager in you /usr/local/.

Any packages that you will install, including python can be found in this directory.

We also need to make sure that /usr/local/ is in our $PATH enviornment before the /bin. In order to do that, run this command.

echo export PATH="/usr/local/bin:$PATH" >> ~/.profile

Now we’re all set to start installing some packages!

3. Install Python

First make sure that homebrew is up to date

$ brew update && brew upgrade

Already up-to-date.

Now we are ready to install python.

$ brew install python

Note

This will install python 2, not python 3.

To install the latest version of Python 3.

$ brew install python3

This will also include pip your python package manager.

First we need to make sure that everything is up to date.

$ pip install --upgrade setuptools
$ pip install --upgrade distribute
$ pip install --upgrade pip
$ pip install --upgrade wheel

Now we’re all ready, we can install py-translate directly from PyPI

$ pip install py-translate

And we’re done!

Usage


translate [-h] [-V] [-l [code]] [source] dest

py-translate
CLI Tool for Google Translate written in Python!

positional arguments

source

Source language code

dest

Destination language code

If only 1 positional argument is specified, it will be assumed to be dest and source will default to english


optional arguments

-h, --help

displays this help message and exit

-v, --version

show program’s version number and exit

-l, --lang [code]

List out available language codes [can output in different languages]

API Documentation

Python API

Code author: Sang Han <jjangsangy@gmail.com>

Translator Co-Routine

translate.translator(source, target, phrase, version='0.0 test', charset='utf-8')

Returns the url encoded string that will be pushed to the translation server for parsing.

List of acceptable language codes for source and target languages can be found as a JSON file in the etc directory.

Some source languages are limited in scope of the possible target languages that are available.

>>> from translate import translator
>>> translator('en', 'zh-TW', 'Hello World!')
    '你好世界!'
Parameters:
  • source (String) – Language code for translation source
  • target (String) – Language code that source will be translate into
  • phrase (String) – Text body string that will be url encoded and translated
Returns:

Request Interface

Return type:

Dictionary

translate.coroutine(func)

Initializes coroutine essentially priming it to the yield statement. Used as a decorator over functions that generate coroutines.

# Basic coroutine producer/consumer pattern
from translate import coroutine

@coroutine
def coroutine_foo(bar):
    try:
        while True:
            baz = (yield)
            bar.send(baz)

    except GeneratorExit:
        bar.close()
Parameters:func (Function) – Unprimed Generator
Returns:Initialized Coroutine
Return type:Function

HTTP Delegation

translate.push_url(interface)

Decorates a function returning the url of translation API. Creates and maintains HTTP connection state

Returns a dict response object from the server containing the translated text and metadata of the request body

Parameters:interface (Function) – Callable Request Interface

Stream Caching

translate.source(target, inputstream=<_io.TextIOWrapper name='<stdin>' mode='r' encoding='ANSI_X3.4-1968'>)

Coroutine starting point. Produces text stream and forwards to consumers

Parameters:target (Coroutine) – Target coroutine consumer
translate.spool(iterable, maxlen=1250)

Consumes text streams and spools them together for more io efficient processes.

Parameters:
  • iterable (Coroutine) – Sends text stream for further processing
  • maxlen (Integer) – Maximum query string size
translate.set_task(translator, translit=False)

Task Setter Coroutine

End point destination coroutine of a purely consumer type. Delegates Text IO to the write_stream function.

Parameters:
  • translation_function (Function) – Translator
  • translit – Transliteration Switch
Type:

Bool

translate.write_stream(script, output='trans')
Parameters:script (Iterable) – Translated Text
Return None:
translate.accumulator(init, update)

Generic accumulator function.

Parameters:
  • init – Initial Value
  • update – Value to accumulate
Returns:

Combined Values

Multitasking

translate.set_task(translator, translit=False)

Task Setter Coroutine

End point destination coroutine of a purely consumer type. Delegates Text IO to the write_stream function.

Parameters:
  • translation_function (Function) – Translator
  • translit – Transliteration Switch
Type:

Bool

Writer

translate.write_stream(script, output='trans')
Parameters:script (Iterable) – Translated Text
Return None:

Language Code Generation

translate.translation_table(language, filepath='supported_translations.json')

Opens up file located under the etc directory containing language codes and prints them out.

Parameters:file (str) – Path to location of json file
Returns:language codes
Return type:dict
translate.print_table(language)

Generates a formatted table of language codes

translate
Access to library is done primarily through the application called translate which will be installed and accessed through a directory under users $PATH envar.

Notes

Release History

1.0.2 (2015-01-02)

  • Happy New Year
  • Created quick benchmarking suite
  • Optimized thread utilization
  • Bug fixes and better IO performance

1.0.1 (2014-12-30)

  • More efficient task processing using map over submit.
  • Seperated IO in coroutine exception blocks.
  • Bug Fixes and Improvements.

1.0.0 (2014-12-18)

  • Bug fix with lines longer than 1000 chars
  • Fixed another unicode bug
  • Improved Python 2/3 Compatability
  • Implemented text transliteration where available
  • Implemented simple File IO
  • Better utilization of thread pools using futures module.
  • Vendorized dependencies
  • Swapped transport API from urllib2 with Requests
  • SSL/TLS integration for secure web requests

0.2.3 (2014-12-08)

  • Bug fix with double output

0.2.2 (2014-12-07)

  • Bug fixes
  • Decreased package size
  • Split translator.py into two seperate modules

0.2.1 (2014-12-04)

  • Added Output Buffer Streaming
  • Utilized Cooperative Multitasking for Coroutines
  • Updated Documentation on API

0.2.0 (2014-11-30)

  • Bug fixes
  • Implmented concurrency based on Asyncronous threads and coroutines
  • Up to 10x performance speedup

0.1.6 (2014-11-30)

  • Bug Fixes
  • Re-implmenenting concurrency models
  • Python 3 is now the base implemntation

0.1.5 (2014-07-18)

  • Language Code Generator Fix

0.1.4 (2014-07-05)

  • General Bug Fixes
  • Speed Improvements
  • Length of multibyte characters correctly represented by spooler
  • Better support for utf-8.

0.1.3 (2014-04-07)

  • Implemented language discovery arg
  • Bug Fixes

0.1.2 (2014-04-04)

  • Documentation reorganization

Bug Fixes

  • Fixed unicode encode/decode errors

0.1.1 (2014-04-03)

  • PyPy-c v2.2 now support

Bug Fixes

  • Quick fix PyPI distribution (huge package sizes)
  • MANIFEST.in now does it job
  • Assorted fixes with methods and scope

0.1.0 (2014-04-02)

  • GTranslate is taken on PyPI.
  • Name changed to py-translate
  • Distributed through PyPI and Wheel
  • More documentation and autoparsing for module functions
  • Separated into logical modules in a package rather than one executable __main__.py

0.0.0 (2014-03-31)

  • Support for Python 2.7 and 3.x
  • Sphinx Documentation hosted
  • Travis CI build passed!
  • Source released on Github

TODO

  • Raise exception if nothing is entered into stdin
  • Write documentation for intro
  • Implement Unit Testing framework with nose
  • Use twine for publishing to PyPI

Indices and tables