From 4ef070cd9127e77bb23cd4d17f08dd100037254c Mon Sep 17 00:00:00 2001 From: ssut Date: Fri, 5 Jun 2015 23:43:05 +0900 Subject: [PATCH] initial commit --- googletrans/__init__.py | 3 + googletrans/translated.py | 23 ++++++++ googletrans/translator.py | 112 ++++++++++++++++++++++++++++++++++++++ googletrans/urls.py | 6 ++ translate | 27 +++++++++ 5 files changed, 171 insertions(+) create mode 100644 googletrans/__init__.py create mode 100644 googletrans/translated.py create mode 100644 googletrans/translator.py create mode 100644 googletrans/urls.py create mode 100755 translate diff --git a/googletrans/__init__.py b/googletrans/__init__.py new file mode 100644 index 0000000..b66e87d --- /dev/null +++ b/googletrans/__init__.py @@ -0,0 +1,3 @@ +"""Free Google Translate API for Python. Translates totally free of charge.""" + +__version__ = 1.0 \ No newline at end of file diff --git a/googletrans/translated.py b/googletrans/translated.py new file mode 100644 index 0000000..dc0279f --- /dev/null +++ b/googletrans/translated.py @@ -0,0 +1,23 @@ +class Translated: + """ + The Translated object, which contains Google Translator's result. + + :param src: source langauge (default: auto) + :param dest: destination language (default: en) + :param origin: original text + :param text: translated text + :param pronunciation: the pronunciation provided by Google Translator + """ + def __init__(self, src, dest, origin, text, pronunciation): + self.src = src + self.dest = dest + self.origin = origin + self.text = text + self.pronunciation = pronunciation + + def __str__(self): + return self.__unicode__() + + def __unicode__(self): + return ''.format( + src=self.src, dest=self.dest, text=self.text, pronunciation=self.pronunciation) \ No newline at end of file diff --git a/googletrans/translator.py b/googletrans/translator.py new file mode 100644 index 0000000..07e06ba --- /dev/null +++ b/googletrans/translator.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +""" +A Translation module. + +You can translate text using this module. + +Basic usage: + >>> from googletrans import translator + >>> translator.translate(u'안녕하세요.') + + >>> translator.translate(u'안녕하세요.', dest='ja') + + >>> translator.translate('veritas lux mea', src='la') + + +Advanced usage: + >>> translations = translator.translate(['The quick brown fox', 'jumps over', 'the lazy dog'], dest='ko') + >>> for translation in translations: + ... print(translation.origin, ' -> ', translation.text) + The quick brown fox -> 빠른 갈색 여우 + jumps over -> 이상 점프 + the lazy dog -> 게으른 개 +""" +import re +import requests +from collections import namedtuple +from future.moves.urllib.parse import quote + +from . import __version__ +from googletrans import urls +from googletrans.translated import Translated + +user_agent = 'PyGt/{0}'.format(__version__) + +EXCLUDES = ['en', 'ca', 'fr'] +RE_SRC = re.compile(',\[\["([\w]{2})"\]') + +__agent = None +__headers = { + 'User-Agent': user_agent, + 'Referer': urls.TRANSLATOR, +} +def agent(): + """ + A requests session for translator + """ + global __agent + # create new object when object doesn't created yet. + if not __agent: + __agent = requests.Session() + # this code may help to avoid a ban. + __agent.get(urls.TRANSLATOR, headers=__headers) + + return __agent + +# translator.translate(text, to='') +def translate(text, dest='en', src='auto'): + """ + Translate the passed text into destination language. + + :param text: the text you want to translate. + you can pass this parameter as a list object, as shown in the advanced usage above. + :param dest: the destination language you want to translate. (default: en) + :param src: the source language you want to translate. (default: auto) + + :rtype: Translated + :rtype: list (when list is passed) + """ + if isinstance(text, list): + result = [] + for item in text: + translated = translate(item, dest=dest, src=src) + result.append(translated) + return result + + result = '' + sess = agent() # acquire requests session + origin = text + text = quote(text) + url = urls.TRANSLATE.format(query=text, src=src, dest=dest) + r = sess.get(url, headers=__headers) + + """ + Resposne Sample (20150605) + $ ./translate "republique" -d ko + + [[["공화국","republique"],[,,"gonghwagug"]],,"fr",,,[["republique",1,[["공화국",1000,true,false],["공화국의",0,true,false],["공화국에",0,true,false],["공화국에서",0,true,false]],[[0,10]],"republique",0,1]],0.94949496,,[["fr"],,[0.94949496]],,,[["명사",[[["communauté","démocratie"],""]],"république"]]] + """ + + # this code will be updated when the format is changed. + # (I know this code is not really efficient and so sketchy.) + translated = r.text.split('[[[')[1][1:].split('"')[0] + # actual source language that will be recognized by Google Translator when the + # src passed is equal to auto. + try: + src = RE_SRC.findall(r.text)[0] + except: pass + + pron = origin + if src not in EXCLUDES: + try: + pron_table = r.text.split('[[[')[1].split('[')[1] + pron = pron_table.split('"')[1].split('"')[0] + except: pass + if dest in EXCLUDES: + pron = translated + + # put final values into new Translated object + result = Translated(src=src, dest=dest, origin=origin, + text=translated, pronunciation=pron) + + return result diff --git a/googletrans/urls.py b/googletrans/urls.py new file mode 100644 index 0000000..3ac1106 --- /dev/null +++ b/googletrans/urls.py @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +""" +Predefined URLs used to make google translate requests. +""" +TRANSLATOR = 'https://translate.google.com/' +TRANSLATE = 'https://translate.google.com/translate_a/single?client=t&sl={src}&tl={dest}&hl={dest}&dt=bd&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&q={query}' diff --git a/translate b/translate new file mode 100755 index 0000000..0c1efcf --- /dev/null +++ b/translate @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import argparse +from googletrans import translator + +def main(): + parser = argparse.ArgumentParser( + description='Python Google Translator as a command-line tool') + parser.add_argument('text', help='The text you want to translate.') + parser.add_argument('-d', '--dest', default='en', + help='The destination language you want to translate. (Default: en)') + parser.add_argument('-s', '--src', default='auto', + help='The source language you want to translate. (Default: auto)') + args = parser.parse_args() + + result = translator.translate(args.text, dest=args.dest, src=args.src) + result = """ +[{src}] {original} + -> +[{dest}] {text} +[pron.] {pronunciation} + """.strip().format(src=result.src, dest=result.dest, original=result.origin, + text=result.text, pronunciation=result.pronunciation) + print(result) + +if __name__ == '__main__': + main()